Issue
I am adding TypeScript to my project for the first time.
Using window.document.getElementById()
to access something results in the error:
Type error: Object is possibly 'null'. TS2531
I searched online but couldn't come to the best solution for this. window
can never be null.
Solution
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
}
Answered By - hackape
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.