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

51,893

Solution 1

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
}

Solution 2

window.document.getElementById("foobar");

Is either returning a HTMLElement or null

As you might used a similar statement before: window.document.getElementById("foobar").value

Typescript is complaining about, that value might not be accessible and you should explicitly check this before.

To avoid this you can do the following:

const element = window.document.getElementById("foobar");

if (element !== null) {
    alert(element.value);
}

Solution 3

Here you have to make sure your window.document.getElementById("id_name")! is set. You can try this

const element = window.document.getElementById("id_name");

if(element){
console.log(element);
}

Solution 4

Typescript is complaining that object, result of window.document.getElementById execution in your case, can be null.

This could be turned off using strictNullChecks flag in your tsconfig.json which I do not recommend.

Alternatively you can do checks at suggested in other answers or starting with Typescript 3.7 use Optional Chaining syntax to make your code more concise:

obj?.doSometething(); //good, will not do something.
obj?.prop = 'plop'; //not good because it does not work with assignments.
Share:
51,893
ghostCoder
Author by

ghostCoder

Love to code and explore. Check out http://thecamelcase.com/

Updated on January 27, 2022

Comments

  • ghostCoder
    ghostCoder over 2 years

    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.