Home > Back-end >  Can I trust Typescript when dealing with a reference to a DOM element?
Can I trust Typescript when dealing with a reference to a DOM element?

Time:03-17

The following function gets a reference to a DOM element and then does stuff:

function getElementAndDoStuff() {
  // element: HTMLElement | null
  const element = document.getElementById('id');

  if(!element) throw new Error('Error.');

  // element: HTMLElement
  element;
}

After the throwing line, element is considered an HTMLElement by TypeScript, however the element may disappear from the DOM at any time, so is it safe to trust TypeScript?

Even if instead of accessing element right after the throwing line, we put random function calls and asyn/await in between?

Are there cases when it's not safe to trust TypeScript?

CodePudding user response:

It is safe to trust it, because whether or not it's in the DOM, it'll still be an HTMLElement.

const element = document.querySelector('div');
console.log(element instanceof HTMLElement);
element.remove();
console.log(element instanceof HTMLElement);
<div>div</div>

If the element is not attached to the DOM, and you try to do something that requires an element currently in the DOM, you will get warned about if. For example, you couldn't do

const parent = document.querySelector('parent');
parent.appendChild(element);

without changing it to something like

const parent = document.querySelector('parent');
if(!parent) throw new Error('Error.');
parent.appendChild(element);

Even if instead of accessing element right after the throwing line, we put random function calls and asyn/await in between?

Yes, that's safe, as long as the variable never gets reassigned - it can't ever get mutated from an HTMLElement to something else, so keeping it typed as such, no matter what other code runs, is safe.

Are there cases when it's not safe to trust TypeScript?

There are generally edge cases in every faucet of programming. Nothing is 100% perfect. TypeScript, being written by humans, has bugs. But given how long it's been worked on, many things have been fixed, and most of those that still exist are relatively unusual to come across in the normal process of writing a script.

In my experience, TypeScript problems are much more frequently along the lines of TypeScript not being able to infer a type properly without a bit of extra help from the programmer, though a type assertion or type guard or something like that. Going the other way around - a type being A despite TypeScript inferring it to be B and definitely not A - is much, much more unusual in a decent codebase (that doesn't, for example, throw around anys and ass liberally). I've written a decent amount of TS and can't remember the last time I ran into that issue, or even if I ever have. There are frequently false-positive type warnings, and very rarely false-negative type inferences.

  • Related