Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StrictNullChecks and getElementById

Tags:

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?

like image 563
skoll Avatar asked Nov 16 '16 19:11

skoll


People also ask

Should I enable strictNullChecks?

If you're starting a new TypeScript project or you find the time to introduce the strictNullChecks flag to your existing project, I would recommend doing so. On the upside you'll get more safety added to your application at compile time, which is almost always a good thing.

Can I use document getElementById in TypeScript?

To use the document. getElementById() method in TypeScript: Use a type assertion to type the selected element correctly. Use a type guard to make sure the variable does not store a null value.

Why does getElementById return null?

HTML DOM Document getElementById() The getElementById() method returns null if the element does not exist.


2 Answers

You can write:

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

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

like image 120
AlexG Avatar answered Oct 06 '22 05:10

AlexG


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!

like image 34
Matthew Layton Avatar answered Oct 06 '22 05:10

Matthew Layton