Search code examples
reactjstypescripteventsmouseevent

How can I type an event with mouseEvent and event.target (react project with typescript)?


I need your help for my project.
I want to close a menu when I click outside.
I write the following code but I have problems with typescript.

The code works when I use any to type the "ev" argument but I know it's not recommanded.

Here my code :

  useEffect(() => {
    const checkIfClickedOutside = (ev: any) => {
      if (isMenuOpen && menuRef.current && !menuRef.current?.contains(ev.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', checkIfClickedOutside);

    return () => {
      document.removeEventListener('mousedown', checkIfClickedOutside);
    };
  }, [isMenuOpen, menuRef]);

I try with MouseEvent but I have this error :

Argument of type 'EventTarget' is not assignable to parameter of type 'Node'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more. 

and this :

const checkIfClickedOutside: (ev: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "mousedown", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'ev' 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 '(ev: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(ev: MouseEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'ev' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more

Can someone help me? Thanks a lot !


Solution

  • Official DOM typings point to a MouseEvent interface when you use addEventListener with mousedown argument.