Search code examples
javascripttypescriptevents

when using event.target it works on website but on code has error


With javascript I check if the user clicks inside 2 divs with event.target, it works but in code it gives this error message:

Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'. Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 44 more.Vetur(2345)

cogsClose() {
    if (
      !document.querySelector(".cogs-window")!.contains(event.target)! &&
      !document.querySelector(".fa-cogs")!.contains(event.target)
    ) {
      document.getElementById("cogs-user")!.classList.add("cogs-hide");
      document.getElementById("cogs-tabs")!.classList.add("cogs-hide");
    }
  }

The error shows on both of the event.target.


Solution

  • Let's check what lib.dom.d.ts says abut that. So the contains functions signature looks like this:

    contains(other: Node | null): boolean;
    

    and typing for mouseEvent's property target is

    readonly target: EventTarget | null;
    

    EventTarget is not compatible type with Node. This is because target don't have to be always Node type as is mention in doc. But if you are sure about the typing then u can just cast that right to Node or HTMLElement or something like that.

    .contains(<Node>(event!.target))
    

    But be careful about that.. Types are here to protect us so signature looks like this for some reason. Same for using ! everywhere..