Question: Without using any
, what is the proper typing for my onMouseMove
function?
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 don't know how to make it happy without using 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'.
What are the proper typescript types for addEventListener mousemove and it's event argument?
Being explicit will set you free:
onMouseMove: { (event: MouseEvent): void } = (event: MouseEvent) => {
}
Or, let TypeScript infer it from assignment 🌹:
onMouseMove = (event: MouseEvent) => {
}