Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda