I am trying to log the event on mousemove
on window
in the console using React with TypeScript. After some research and looking at similar questions I thought I could use MouseEvent
as the type for the event passed on to the listener.
useEffect(() => {
const onMouseMove = (e: MouseEvent) => {
e.preventDefault();
console.log(e);
};
window.addEventListener("mousemove", onMouseMove);
return () => {
window.removeEventListener("mousemove", onMouseMove);
};
}, []);
But when running, it prompts me the following error:
const onMouseMove: (e: MouseEvent) => void
No overload matches this call.
Overload 1 of 2, '(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type '(this: Window, ev: MouseEvent) => any'.
Types of parameters 'e' and 'ev' are incompatible.
Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(e: MouseEvent) => void' is not assignable to type 'EventListener'.
Types of parameters 'e' and 'evt' are incompatible.
Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more
I tried updating my event listener syntax with some of the suggestions but none of them seem to fix the problem.
const onMouseMove = (e: MouseEvent): any => {} // any as return type
const onMouseMove: EventListener = (e: MouseEvent) => {} // type as EventListener
import { MouseEvent } from "react";
if so, remove that import MouseEvent, the event type for window is MouseEvent (DOM) not the one from React – BlockMouseEvent
from React, thank you! – Codeclination