typescriptmouseeventinstanceofhtmlelements

Why does typechecking with 'instanceof' works differently for logical not operator and strict false equality check?


I have the following code:

function handleIndexClick(event: MouseEvent) {
  if (event.target instanceof HTMLElement === false) {
    return;
  }
  
  // here will be a type error: Property 'dataset' does not exist on type 'EventTarget'.
  if (event.target.dataset.index) {
    console.log(event.target.dataset.index);
  };
};

However if I replace the first condition with if (!(event.target instanceof HTMLElement) the error is gone.

Why does it work this way?

Try in TS Playground


Solution

  • This is either a very-low-priority bug as described in microsoft/TypeScript#31105 (it's on the Backlog, meaning it's not scheduled to be fixed in any upcoming release... and I don't see evidence of any work being done here); or it's an intentionally missing feature as described in microsoft/TypeScript#9508. According to that issue:

    This doesn't seem common enough to support. In most cases === true [and presumably === false] is a code smell and doesn't appear often enough to justify the extra complexity to support it.

    It's not usually idiomatic JavaScript to do a boolean test on b === false or b === true. If you have a boolean it is more common to check it as either !b or b in your condition, as you noted.