StrictNullChecks and getElementById

It is because document.getElementById(...); can return an instance of HTMLElement if the element is found, or null if it is not. Since this API is not under your control, you will have to modify your code to allow the element to be nullable:

var el: HTMLElement | null = document.getElementById("...");

You can also create your own nullable type aliases:

type NullableHTMLElement = HTMLElement | null;
var el: NullableHTMLElement = document.getElementById("...");

Or better still you could use the solution provided by AlexG which is even better!


You can write:

var el = document.getElementById('element_id')!;

The ! means "trust me, this is not a null reference"