Treat an Object as HTML Input Element in TypeScript

Last updated on 3 Jan, 2023

If the id of an input element is myAge, we can get the value of the text box using:

const age = document.getElementById("myAge");

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;
--- ○ ---