Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type error: Object is possibly 'null'. TS2531 for window.document

Tags:

Adding Typescript to my project for the first time.

At one place i have used window.document.getElementById to access something. And its giving this error.

Type error: Object is possibly 'null'.  TS2531 

I searched online but couldn't come to the best solution for this. window can't ever be null. How can i fix this error? Pls help.

like image 926
ghostCoder Avatar asked Apr 09 '19 09:04

ghostCoder


People also ask

How do you fix error object is possibly null?

The error "Object is possibly 'null'" occurs when we try to access a property on an object that may have a value of null . To solve the error, use the optional chaining operator to short-circuit if the reference is equal to null , e.g. emp?. address?. country .

Why does getElementById return null?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.


1 Answers

TS is doing its job and tells you that window.document.getElementById("foobar") COULD return something that is null.

If you are absolutely sure that #foobar element DOES exist in your DOM, you can show TS your confidence with a ! operator.

// Notice the "!" at the end of line const myAbsolutelyNotNullElement = window.document.getElementById("foobar")! 

Or, you can add a runtime nullable check to make TS happy

const myMaybeNullElement = window.document.getElementById("foobar")  myMaybeNullElement.nodeName // <- error!  if (myMaybeNullElement === null) {   alert('oops'); } else {   // since you've done the nullable check   // TS won't complain from this point on   myMaybeNullElement.nodeName // <- no error } 
like image 169
hackape Avatar answered Oct 25 '22 11:10

hackape