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?
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.
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.
HTML DOM Document getElementById() The getElementById() method returns null if the element does not exist.
You can write:
var el = document.getElementById('element_id')!;
The ! means "trust me, this is not a null reference"
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With