Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!