skoll skoll - 23 days ago 6
TypeScript Question

StrictNullChecks and getElementById

With StrictNullChecks enabled in TypeScript 2.0, the code

var el: HTMLElement = document.getElementById('element_id');


produces the error

Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
Type 'null' is not assignable to type 'HTMLElement'.


Why is this and how can I get the code to compile without making
el
nullable?

Answer

You can write:

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

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