addEventListener的mousemove事件和它的事件参数应该使用哪些适当的TypeScript类型?

31
问题:在不使用任何代码的情况下,如何正确输入我的onMouseMove函数?
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);
  }
}

Typescript对我的类型有意见,而且我不知道如何在不使用any的情况下让它满意。
main.ts(38,3): error TS2322: Type '(event: MouseEvent) => void' is not assignable to type 'EventListener'.
  Types of parameters 'event' and 'evt' are incompatible.
    Type 'Event' is not assignable to type 'MouseEvent'.
      Property 'altKey' is missing in type 'Event'.

2
事件处理程序接收一个 MouseEventInit 类型。告诉参数它是一个 MouseEvent。 …addEventListener("mousemove", (ev: MouseEventInit): void => dosomething(ev as MouseEvent)); - Denis Giffeler
4个回答

31

适用于addEventListener的mousemove事件及其事件参数的TypeScript类型是什么?

明确会让你自由:

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

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

onMouseMove = (event: MouseEvent) => {
}

6

我发现使用 MouseEventInit 作为事件类型可以解决这个问题。这个类型来自于 TypeScript 的 lib.dom.ts 。我正在使用 TypeScript 4.5.5。

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

1
preventDefault()MouseEventInit 上不存在 :( - James Gentes

5
在这种情况下,不需要明确指定类型,因为当您将处理程序分配给事件时,函数的类型将得到检查。例如,请查看onclick:
onclick: (this: HTMLElement, ev: MouseEvent) => any;

有三种类型的onclick处理程序。当您编写以下内容时:
myDomElement.onclick = myFunction;

TypeScript 会检查 myFunction 是否匹配 onclick 类型。因此,只需让 TypeScript 推断类型,就像另一个答案所说的那样。


1

我最近在使用React时遇到了这个问题,想提醒大家,在给window添加鼠标事件监听器时,不需要导入React组件,而是需要使用全局的DOM MouseEvent类型。如果你像我一样使用VSCode,可能会意外地从React中自动导入MouseEvent!如果是这样,请删除该导入语句,然后就可以愉快地继续编码了。希望这能帮助到有需要的人,祝好!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接