skoll skoll - 1 year ago 97
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

Answer Source

You can write:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download