Home > Back-end >  Object is possibly 'null'. TS2531 React with TypeScript
Object is possibly 'null'. TS2531 React with TypeScript

Time:09-30

I'm building a application with React and TypeScript ... When I try to .innerHTML or innerText something I got this error:

Object is possibly 'null'. TS2531

I'm new with TypeScript and I don't know what I should do, I know it's something related with interface ... but I can't find a specific resolve.

If someone can solve my problem with my code it would be great.

Thanks in advance . I let my code below:

const Home: FC = () => {
      const percentage = 91;
    
      const startingMinutes = 25;
      let time = startingMinutes * 60;
      const countdownEl = document.getElementById("countdown");
    
      const updateCountDown = () => {
        const minutes = Math.floor(time / 60);
        let seconds = time % 60;
        
        countdownEl.innerHTML=`${minutes}: ${seconds}`;
        time--;
      };
    
      const changeTimer = () => {
        var timer = document.getElementById("countdown");
        var time = document.getElementById("time");
    
        // timer.innerText=time;
      };

CodePudding user response:

document.getElementById can theoretically return null if no element exists with the given id.

TypeScript is smart enough to see that you're not performing any validation before using a potential null object, i.e. countdownEl.innerHTML=`${minutes}: ${seconds};` .

There are 2 principal ways to fix this:

  1. Guard your code with if (countdownEl) {} to ensure the respective code only gets executed when countdownEl is truthy.
  2. Explicitly cast the result of document.getElementById if if should "always" return a non-null value, i.e. const countdownEl = document.getElementById("countdown") as HTMLElement;

CodePudding user response:

You only need to make sure that the the .innerText only runs when timer is not null, a simple if statement will do the trick. if(timer){timer.innerText = time }

  • Related