Open ImLunaHey opened 9 months ago
Currently the annoying hack i need to use is JSON.parse(localStorage.getItem('a') || 'null');
JSON.parse does call ToString(argument) before actual parse begins.
https://tc39.es/ecma262/multipage/structured-data.html#sec-json.parse
- Let jsonString be ? ToString(text).
Following cases are where ToString returns valid JSON values. https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tostring
- If argument is null, return "null".
- If argument is true, return "true".
- If argument is false, return "false".
- If argument is a Number, return Number::toString(argument,
10
).- If argument is a BigInt, return BigInt::toString(argument,
10
).
localStorage.setItem('a', null);
const result = JSON.parse(localStorage.getItem('a'));
console.log(result === null)
// true
localStorage.setItem('a', "null");
const result = JSON.parse(localStorage.getItem('a'));
console.log(result === null)
// true
The purpose is not to make every non throwing ECMAscript code pass typescript checking.
ts-reset smooths over these hard edges
I think JSON.parse
typing should indeed only accept strings by default, because this is what most users would expect as "type-safe".
If one wants to get advantage of string coercion this can be easily done by JSON.parse(String(value))
, no need to use value-specific hacks like || 'null'
.
@NoamAnisfeld that makes it less typesafe. Typesafety should reflect what actually happens.
Currently this fails type checking yet it works in all js environments I've tried.