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

We introduced Typescript to a work project, and an error appeared. It returns Type error: Object is possibly ‘null’. TS2531 for window.document. We explain what causes it and how to fix it. Let’s begin!

What Causes The Error?

The error happened when we were introducing Typescript into our work project. It returns like this.

Type error: Object is possibly 'null'.  TS2531

How To Fix “Type error: Object is possibly ‘null’. TS2531 for window.document”?

The Typescript is functioning perfectly by informing you of the window.document.getElementById(“foobar”) MAY RETURN NULL. If you are certain that the #foobar element exists, you may demonstrate your certainty to TS by using the! operator.

Solution 1

For the first solution, when Typescript successfully informs you about the problem, you may demonstrate your certainty to TS by using the!

// Notice the "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
Alternatively, you may make TS satisfied by including a runtime nullable test.
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”) returns either an HTMLElement or null. You may have made a similar command before: window.document.getElementById(“foobar”).value. 

Typescript is objecting because the value may not be available, and you must explicitly confirm this before proceeding. You may avoid this by executing the following command.

const element = window.document.getElementById("foobar");
if (element !== null) {
    alert(element.value);
}

Conclusion

If you run into the Type error, the Object is possibly ‘null’. TS2531 for window.document, there are a few solutions you can apply to resolve it. You may demonstrate by using the ! and including a runtime test or check if you are using the same command.

We hope our answer satisfies you! Please feel free to add your questions and your most suitable solutions in the comment section! Thank you!


Related articles

Scroll to Top