0

What is the correct type for window.onClick, my linter is not happy with any

import React, { useContext, useState } from 'react';
import { Link } from 'react-router-dom';
import { Global } from '../globalState';
import { Dispatch, LOGGED_IN, SET_MODAL } from '../globalState';

interface PropsInterface {
  avatar: string;
  loggedIn: boolean;
  fullName: string;
}

const TopNav: React.FC<PropsInterface> = (props: PropsInterface) => {
...
window.onclick = (event: any) => {
//                        ^
//                        What is the correct type ??       
    if (
      event.target.id !== 'dropdown'
    ) {
      setState((prev) => ({
        ...prev,
        dropDownStatus: false,
      }));
    }
  };
Bill
  • 4,614
  • 13
  • 77
  • 132

2 Answers2

1

This is defined in the default DOM type definition.

In the most recent version you can find this definition at line 5903 of the lib.dom.d.ts:

...

/**
 * Fires when the user clicks the left mouse button on the object
 * @param ev The mouse event.
 */
onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;

...

So the correct type would be MouseEvent:

window.onclick = (event: MouseEvent) => { }

If you really want to map the id of the target, you can do something like:

window.onclick = (event: MouseEvent & { target: {id: string}}) => { }

TL;DR

This part doesn't answer the question, but helps to address further trouble.

You want that the dropdown closes, if anything but the dropdown was clicked, right? I think you are better of with adding a reference to the dropdown and compare this instead of the id:

Community
  • 1
  • 1
Robin
  • 8,162
  • 7
  • 56
  • 101
  • I get a new error `Property 'id' does not exist on type 'EventTarget'.ts(2339)` on `event.target.id` – Bill Dec 15 '19 at 15:07
  • @Bill: Please open another question, if you have troubles implementing off click handling, as this question is about something else. – Robin Dec 15 '19 at 15:27
1

For synthetic elements, you can use React.MouseEvent.

sunknudsen
  • 6,356
  • 3
  • 39
  • 76