Type-safe way to use getElementById in TypeScript

If you would like to call document.getElementById and use its element-specific (form, select, input, etc.) properties, there’s no way for the TypeScript compiler to know the type of element. To use these properties in a type-safe way, add some flow control to facilitate type inference.

For example, we would like to retrieve the value of an input. The following:

const element = document.getElementById('my-id');
console.log(`Input value: ${element.value}`); 

causes the TypeScript compiler to complain:

'element' is possibly 'null'.
Property 'value' does not exist on type 'HTMLElement'.

This can be fixed by adding some flow control to facilitate type inference:

const element = document.getElementById('my-id');
if(element !== null && element instanceof HTMLInputElement) {
    console.log(`Input value: ${element.value}`); 
}