Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda