Type error: Object is possibly 'null'. TS2531 for window.document
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);
}
It is because you have to set the type.
const checkbox = document.getElementById("toggleFilter") as HTMLInputElement
checkbox.checked = true
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
}