-
Notifications
You must be signed in to change notification settings - Fork 13.3k
JSON.stringify should disallow BigInt value #63333
Description
⚙ Compilation target
es2023
⚙ Library
lib.es5.d.ts
Missing / Incorrect Definition
JSON.stringify is correctly marked with @throws {TypeError} If a circular reference or a BigInt value is found., but it types its input value parameter as any. That type could be improved so that BigInt can't even be passed into the function (turning one runtime error into a compiletime error).
Perhaps even every type that contains a BigInt can and should be excluded. I'm not very good at TypeScript but that might be possible.
Note that if a replacer function is specified, this complicates the situation somewhat.
This issue is distinct from the perennial proposal to correctly treat undefined in JSON.stringify (eg #18879). Hopefully, the false-positive impact of this one should be much lower, and thus it can be accepted.
Sample Code
//These are runtime errors, but TypeScript doesn't complain.
//"Uncaught TypeError: Do not know how to serialize a BigInt"
JSON.stringify(1n);
JSON.stringify([1n]);Documentation Link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/BigInt_not_serializable
https://tc39.es/ecma262/multipage/structured-data.html#sec-json.stringify
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify