total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.74k stars 117 forks source link

allow passing `null` to `JSON.parse()` #173

Open ImLunaHey opened 9 months ago

ImLunaHey commented 9 months ago

Currently this fails type checking yet it works in all js environments I've tried.

JSON.parse(localStorage.getItem('a'));
ImLunaHey commented 9 months ago

Currently the annoying hack i need to use is JSON.parse(localStorage.getItem('a') || 'null');

qb20nh commented 6 months ago

JSON.parse does call ToString(argument) before actual parse begins.

https://tc39.es/ecma262/multipage/structured-data.html#sec-json.parse

  1. Let jsonString be ? ToString(text).

Following cases are where ToString returns valid JSON values. https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tostring

  1. If argument is null, return "null".
  2. If argument is true, return "true".
  3. If argument is false, return "false".
  4. If argument is a Number, return Number::toString(argument, 10).
  5. If argument is a BigInt, return BigInt::toString(argument, 10).
ImLunaHey commented 6 months ago
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
qb20nh commented 6 months ago

The purpose is not to make every non throwing ECMAscript code pass typescript checking.

ImLunaHey commented 6 months ago

ts-reset smooths over these hard edges

NoamAnisfeld commented 4 months ago

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'.

ImLunaHey commented 4 months ago

@NoamAnisfeld that makes it less typesafe. Typesafety should reflect what actually happens.