Adding Typescript to my project for the first time.
At one place i have used window.document.getElementById
to access something. And its giving this error.
Type error: Object is possibly 'null'. TS2531
I searched online but couldn't come to the best solution for this. window can't ever be null. How can i fix this error? Pls help.
The error "Object is possibly 'null'" occurs when we try to access a property on an object that may have a value of null . To solve the error, use the optional chaining operator to short-circuit if the reference is equal to null , e.g. emp?. address?. country .
This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With