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

231
Vistas
TypeScript and unary operator on nullable value

When writing this code:

const num = +localStorage.getItem('whatever');

TypeScript complains about the return value of getItem that is possibly null as shown in this TypeScript playground. However, the unary operator is perfectly able to handle this case. Indeed, +null === 0

console.log(+null === 0);

Why is that, and how to fix?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Wrap it inside a Number class and use a exclamation at the end to show that result should be shown, just like show below.

const num = +Number(localStorage.getItem('whatever'))!;
about 4 years ago · Juan Pablo Isaza Denunciar

0

TypeScript restricts type conversion for potentially nullable values for avoid typing issues. If you are surely want to convert value, you can use:

  1. Type assertion using as keyword:

    const num = +(localStorage.getItem('whatever') as unknown as string);
    

    Playground

  2. Using Non-null assertion operator:

    const num = +localStorage.getItem('whatever')!;
    

    Playground

  3. Using Number primitive wrapper:

    const num = Number(localStorage.getItem('whatever'));
    

    Playground

All methods will convert null (also any nullish value) to 0. And you need to handle possible NaN in any case.

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