addEventListener mousemove及其事件参数的正确打字稿类型是什么?

时间:2018-03-11 23:41:49

标签: typescript mouseevent mousemove tsc static-typing

问题:不使用lines = [ ['top-L','top-M','top-R'], ['top-L', 'mid-L', 'low-L'] ... etc ... ] for line in lines: if len(set(self.board[x] for x in line])) == 1: print("Winner:", self.board[line[0]]) any功能的正确输入是什么?

onMouseMove

Typescript抱怨我的类型,我不知道如何使用任何一种方式让它变得快乐。

export class Main {
  private dTimer: number;

  constructor() {
    this.init();
  }

  private init() {
    this.mouseHandlers();
  }

  private mouseHandlers() {
    document.addEventListener('mousemove', this.onMouseMove)
  }

  private onMouseMove: EventListener = (event: MouseEvent) => {
    clearTimeout(this.dTimer);
    this.dTimer = setTimeout(() => {
      console.log(event.pageX, event.pageY)
    }, 500);
  }
}

2 个答案:

答案 0 :(得分:3)

  

addEventListener mousemove和它的事件参数有哪些正确的打字稿类型?

明确会让你自由:

onMouseMove: { (event: MouseEvent): void } = (event: MouseEvent) => {
}

或者,让TypeScript从赋值中推断它:

onMouseMove = (event: MouseEvent) => {
}

答案 1 :(得分:2)

在这种情况下不需要explcit类型,因为在将处理程序分配给事件时将检查函数的类型。以onclick

为例
onclick: (this: HTMLElement, ev: MouseEvent) => any;

onclick处理程序的类型。当你写下:

myDomElement.onclick = myFunction;

只要myFunction匹配onclick类型,TypeScript就会检查。所以,正如另一个答案所说的那样,让TypeSript推断类型。