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 dunno how to make it happy w/o 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'.
Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent . As well as SyntheticEvent , for all other events.
The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.
What is Mousemove event in Javascript? The mousemove event occurs whenever the mouse pointer moves within the selected element. The mousemove() method triggers the mousemove event, or attaches a function to run when a mousemove event occurs. Note: Each time a user moves the mouse one pixel, a mousemove event occurs.
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) => {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With