typescript 使用HTMLElement.prototype添加多个eventListener不起作用

ukdjmx9f  于 2022-12-30  发布在  TypeScript
关注(0)|答案(2)|浏览(145)

我扩展了HTMLElement原型以添加多个eventListener
我的方法

declare global {
  HTMLElement {
    addEventListeners(): any // with a 's'
  }
}

type CallBackFunction<T = void> = () => T

HTMLElement.prototype.addEventListeners() = function(events: Array<HTMLElementEventMap>, callback: CallBackFunction) {
  events.forEach((event) => {
    this.addEventListener(event, callback)
  })
}

但是上面的代码给了我:

  • Type '(events: Array<keyof HTMLElementEventMap>, callback: CallBackFunction) => void' is not assignable to type '() => any'
  • Object is possibly 'undefined'

我第一次尝试

type CallBackFunction<T = any> = () => T

declare global {
  HTMLElement {
    addEventListeners(): void // with a 's'
  }
}

也解决了第二个错误,我甚至把检查,但仍然没有运气!

if (typeof this !== 'undefined') {
  this.addEventListener(event, callback)
}
jyztefdp

jyztefdp1#

我想这就是你要找的

declare global {
  interface HTMLElement {
    addEventListeners<K extends keyof HTMLElementEventMap>(type: K[], listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
  }
}

HTMLElement.prototype.addEventListeners = function (events, listener) {
  events.forEach((event) => {
    this.addEventListener(event, listener);
  });
};

用法

document.querySelector('button').addEventListeners(['click', 'focus'], () => {
 //do something
});
cwxwcias

cwxwcias2#

他们期望函数不返回任何内容(void)。因此,尝试以下操作

相关问题