Home > Net >  Object is possibly 'null' (undefined)
Object is possibly 'null' (undefined)

Time:10-06

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";

  }

CodePudding user response:

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';

CodePudding user response:

Just put this condition and it's work fine for you.

darkMode() {
    const text1 = document.querySelector("#text");
    if(text1){
       text1.style.color = "white";
    }
}
  • Related