Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Object is possibly 'null'. TS2531 React with TypeScript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report

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 }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!