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