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

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
}

Leave a Comment