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?
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.