Issue
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?
Solution
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 HTMLInputElementmeans store inaaHTMLElementcasted asHTMLInputElement. With type inference of TypeScript,awould be of typeHTMLInputElement.const a: HTMLInputElement = document.getElementById("input1")!means you are storing in aHTMLInputElementvariable, aHTMLElementvalue. Thats's why it's yelling at you.
Answered By - yousoumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.