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

100
Visualizações
Type assertion works but annotation does not with HTMLElement

This code works:

const a = document.getElementById("input1")! as HTMLInputElement

However this one throws an error:

const a: HTMLInputElement = document.getElementById("input1")! 

The error reads:

Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 52 more

Can anyone explains why please? Does this mean that with type annotation here, I have to manually specify all those properties? And if so, how would I do it?

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

0

When you make a dom query like document.getElementById("input1"), the type you get is HTMLElement | null. With the help of !, you are telling TypeScript to ignore the possibility that it could be null. Now the difference between your attempts is that:

  • const a = document.getElementById("input1")! as HTMLInputElement means store in a a HTMLElement casted as HTMLInputElement. With type inference of TypeScript, a would be of type HTMLInputElement.

  • const a: HTMLInputElement = document.getElementById("input1")! means you are storing in a HTMLInputElement variable, a HTMLElement value. Thats's why it's yelling at you.

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