axtck
axtck

Reputation: 3965

TypeScript mousemove event on window

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

Upvotes: 10

Views: 11848

Answers (1)

somallg
somallg

Reputation: 2043

Please note that React has it's own definition of MouseEvent (and other Event as well)

When you add event handler to React Element you have to use React Event

<div onClick={(e: React.MouseEvent) => { console.log(e) }></div>

But if you add event listener using DOM API, make sure it come from DOM

  // DOM Event not to be confused with React.MouseEvent
  const onMouseMove = (e: MouseEvent) => {
    e.preventDefault();
    console.log(e);
  };

  window.addEventListener("mousemove", onMouseMove);

  return () => {
    window.removeEventListener("mousemove", onMouseMove);
  };

TypeScript supports DOM event of of the box. In case you import Event from react

import { MouseEvent } from 'react';

This will override MouseEvent of DOM and TypeScript will not happy since those 2 types are differents

Upvotes: 21

Related Questions