When utilizing TypeScript, it is important to note that
window.document.getElementById("foobar")
has the potential to return
null
.
If you are confident that the #foobar
element does indeed exist in your DOM, you can demonstrate this certainty to TypeScript by using the !
operator.
// Utilize "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
Alternatively, you can incorporate a runtime nullable check to satisfy TypeScript's requirements
const myMaybeNullElement = window.document.getElementById("foobar")
myMaybeNullElement.nodeName // <- error!
if (myMaybeNullElement === null) {
alert('oops');
} else {
// Following the nullable check, TypeScript will no longer raise complaints
myMaybeNullElement.nodeName // <- no error
}