我有这个 Typescript 代码:
const pasteFn = (e: ClipboardEvent) => {
const { clipboardData } = e;
const text = clipboardData?.getData('text/plain');
console.log(text);
};
window.addEventListener('paste', pasteFn);
我疯狂地搜索并尝试了所有示例,但我不明白我得到的错误:
No overload matches this call.
Overload 1 of 2, '(type: keyof WindowEventMap, listener: (this: Window, ev: Event | DeviceMotionEvent | DeviceOrientationEvent | GamepadEvent | ... 23 more ... | StorageEvent) => any, options?: boolean | ... 1 more ... | undefined): void', gave the following error.
Argument of type '"paste"' is not assignable to parameter of type 'keyof WindowEventMap'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(e: ClipboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(e: ClipboardEvent) => void' is not assignable to type 'EventListener'.
Types of parameters 'e' and 'evt' are incompatible.
Property 'clipboardData' is missing in type 'Event' but required in type 'ClipboardEvent'.ts(2769)
lib.dom.d.ts(3747, 14): 'clipboardData' is declared here.
最佳答案
粘贴事件在文档上可用,在窗口上不可用。 使用:
window.document.addEventListener('paste', pasteFn);
paste
在接口(interface) DocumentAndElementEventHandlersEventMap
中定义:
interface DocumentAndElementEventHandlersEventMap {
"copy": ClipboardEvent;
"cut": ClipboardEvent;
"paste": ClipboardEvent;
}
此接口(interface)由 HTMLEventMap
和 DocumentEventMap
扩展,而不是由 WindowEventMap
扩展
关于typescript - 无法让粘贴事件在 Typescript 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74809554/