Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Can I trust Typescript when dealing with a reference to a DOM element?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda