Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow passing null to JSON.parse() #173

Open
ImLunaHey opened this issue Oct 16, 2023 · 7 comments · May be fixed by #174
Open

allow passing null to JSON.parse() #173

ImLunaHey opened this issue Oct 16, 2023 · 7 comments · May be fixed by #174

Comments

@ImLunaHey
Copy link

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

JSON.parse(localStorage.getItem('a'));
@ImLunaHey
Copy link
Author

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

@ImLunaHey ImLunaHey linked a pull request Oct 18, 2023 that will close this issue
@qb20nh
Copy link

qb20nh commented Jan 23, 2024

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
Copy link
Author

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
Copy link

qb20nh commented Jan 30, 2024

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

@ImLunaHey
Copy link
Author

ts-reset smooths over these hard edges

@NoamAnisfeld
Copy link

NoamAnisfeld commented Mar 18, 2024

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants