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

229
Views
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 answers
Answer question

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 Report

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 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!