skoll skoll - 4 months ago 34
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


You can write:

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

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