0

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

1
  • I agree with @David Remie, casting needs to be done. Also I think you are trying to refer the DOM element, even before it is mounted. Try accessing DOM element using a ref or in a useEffect or useLayoutEffect hook. Commented Sep 29, 2021 at 7:06

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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 }

Comments

0

This will resolve the issue

const countdownEl = document.getElementById("countdown") as HTMLElement;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.