'Object is possibly 'null' (undefined)
See, this is my code and it is saying few errors, which are: Object is possibly 'null', Property 'style' does not exist on type 'Element'. It is very irritating
darkMode() {
const text1 = document.querySelector("#text");
text1.style.color = "white";
}
Solution 1:[1]
That is because there is no way TypeScript will know beforehand, that an element on the page will match the #text
selector. Moreover, document.querySelector()
returns Element
, which the style
property does not exist.
To fix the typing returned, you will need to manually typecast it to HTMLElement
, i.e.:
const text1 = document.querySelector('#text') as HTMLElement;
Additional note: Casting it to HTMLElement
also solve the null/undefined complaint, but this is only safe if you are yourself 100% sure the element will return an element. Otherwise, you need to do this:
const text1 = document.querySelector('#text') as HTMLElement | null;
if (text1) text1.style.color = 'white';
Solution 2:[2]
Just put this condition and it's work fine for you.
darkMode() {
const text1 = document.querySelector("#text");
if(text1){
text1.style.color = "white";
}
}
Solution 3:[3]
For those that are interested in one line. You do it like this
(document.querySelector('#text') as HTMLElement | null)?.style.color = 'white';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Aman Gojariya |
Solution 3 | Sirjiskit |