typescript addEventListener mousemove 及其事件参数的正确打字稿类型是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49226309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the proper typescript types for addEventListener mousemove and it's event argument?
提问by Matthew Harwood
Question:Without using any
, What is the proper typing for my onMouseMove
function?
问题:不使用any
,我的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 is complaining about my types and I dunno how to make it happy w/o using any.
Typescript 抱怨我的类型,我不知道如何在不使用任何类型的情况下让它开心。
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'.
回答by basarat
What are the proper typescript types for addEventListener mousemove and it's event argument?
addEventListener mousemove 及其事件参数的正确打字稿类型是什么?
Being explicit will set you free:
明确会让你自由:
onMouseMove: { (event: MouseEvent): void } = (event: MouseEvent) => {
}
Or, let TypeScript infer it from assignment :
或者,让 TypeScript 从赋值中推断:
onMouseMove = (event: MouseEvent) => {
}
回答by Pavel
There is no need for explcit type in this case, because type of your function will be checked when you assign your handler to event. Look for example to onclick
:
在这种情况下不需要显式类型,因为当您将处理程序分配给事件时,将检查函数的类型。寻找例如onclick
:
onclick: (this: HTMLElement, ev: MouseEvent) => any;
There type of onclick
handler. When you will write:
有类型的onclick
处理程序。什么时候写:
myDomElement.onclick = myFunction;
TypeScript will check whenever myFunction
match onclick
type. So, just let TypeSript infer type, as another answer said.
TypeScript 会在myFunction
匹配onclick
类型时进行检查。所以,正如另一个答案所说,让 TypeSript 推断类型。