If the id
of an input element is myAge
, we can get the value of the text box using:
const age = document.getElementById("myAge");
console.log(age.value);
But, TypeScript is not sure if age
will always contain a property called value
. Due to that reason TypeScript will throw an error in second line.
We can do type casting and tell TypeScript that age
is a HTML input using HTMLInputElement
.
const age = document.getElementById("myAge") as HTMLInputElement;
console.log(age.value);