Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda