网站搜索

Typescript handleEvent 定义


我有这段代码:

class myClass {
    private handleEvent(e: Event) {
        console.log(e)
    }
    constructor() {
        document.body.addEventListener(`click`, this);
    }
}

如何正确声明而不出错?

No overload matches this call.
  Overload 1 of 2, '(type: "click", listener: (this: HTMLElement, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type 'this' is not assignable to parameter of type '(this: HTMLElement, ev: MouseEvent) => any'.
      Type 'myClass' is not assignable to type '(this: HTMLElement, ev: MouseEvent) => any'.
        Type 'myClass' provides no match for the signature '(this: HTMLElement, ev: MouseEvent): any'.
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type 'this' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type 'myClass' is not assignable to type 'EventListenerOrEventListenerObject'.
        Type 'myClass' is not assignable to type 'EventListenerObject'.
          Type 'this' is not assignable to type 'EventListenerObject'.
            Type 'myClass' is not assignable to type 'EventListenerObject'.
              Property 'handleEvent' is private in type 'myClass' but not in type 'EventListenerObject'.
'handleEvent' is declared but its value is never read.

操场

答案#1

你需要将 function 作为你的处理程序传递。this 指向你的 myClass,而不是其内部的 handleEvent 函数。

尝试以下内容 :-

class myClass {
    private handleEvent(e: Event) {
        console.log(e)
    }
    constructor() {
        document.body.addEventListener(`click`, this.handleEvent);
    }
}

可以从你的错误输出行推断出这一点 :-

Type 'myClass' is not assignable to type '(this: HTMLElement, ev: MouseEvent) => any'.

根据你的评论,handleEvent 应该是 public 而不是 private,正如这一错误行所指出的 :-

Property 'handleEvent' is private in type 'myClass' but not in type 'EventListenerObject'.
class myClass {
    public handleEvent(e: Event) {
        console.log(e)
    }
    constructor() {
        document.body.addEventListener(`click`, this);
    }
}