23

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?

skoll
  • 1,862
  • 3
  • 26
  • 31

3 Answers3

41

You can write:

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

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

AlexG
  • 2,681
  • 20
  • 17
2

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!

Community
  • 1
  • 1
Matthew Layton
  • 32,574
  • 37
  • 140
  • 255
1

I know it's already late, I hope it will help someone else. For my scenario, I want to replace an input value... so the above answer threw one more error like "Property 'value' does not exist on type 'HTMLElement'." So I tried like below and it worked for me.

const el = document.getElementById("my_el_id") as any;
if(el){ //Even this condition not required
  el.value = "New value";
}
Jaison James
  • 3,635
  • 4
  • 30
  • 46