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?
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'))!;
TypeScript restricts type conversion for potentially nullable values for avoid typing issues. If you are surely want to convert value, you can use:
Type assertion using as keyword:
const num = +(localStorage.getItem('whatever') as unknown as string);
Using Non-null assertion operator:
const num = +localStorage.getItem('whatever')!;
Using Number primitive wrapper:
const num = Number(localStorage.getItem('whatever'));
All methods will convert null (also any nullish value) to 0. And you need to handle possible NaN in any case.