typescript - 无法让粘贴事件在 Typescript 中工作

标签 typescript

我有这个 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)由 HTMLEventMapDocumentEventMap 扩展,而不是由 WindowEventMap 扩展

关于typescript - 无法让粘贴事件在 Typescript 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74809554/

相关文章:

Typescript - 计算算术表达式

typescript - JavaScript 和 Typescript 中模块导入的区别?

node.js - 队列消费者中的 Nestjs Shell 命令

Angular 2自定义管道在对象保存之前不更新

javascript - 组合两个对象数组以获得所有可能的结果

node.js - Docker + 私有(private) npm 包 = 找不到模块/找不到模块

angular - 异步自定义验证导致控制台错误 : "Cannot read property ' required' of null at Object. eval [as updateDirectives]”

javascript - 如何让 Angular2 在生成的分发文件夹中工作?

javascript - 更改超时时间

javascript - 将背景图像与 ngStyle 一起使用会返回未定义