-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
JSON.stringify currently has type:
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;For all inputs (including null) except undefined, this type is correct. However, JSON.stringify(undefined) returns undefined. Therefore, the return type of JSON.stringify should be changed to string | undefined.
Solution 1: Change return type for existing overloads
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string | undefined;
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string | undefined;Solution 2 (untested): Only change the return type for undefined inputs
stringify(value: {} | null, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
stringify(value: {} | null, replacer?: (number | string)[] | null, space?: string | number): string;
stringify(value: undefined, replacer?: (this: any, key: string, value: any) => any, space?: string | number): undefined;
stringify(value: undefined, replacer?: (number | string)[] | null, space?: string | number): undefined;TypeScript Version: 3.6.3 and 3.7-Beta (on typescript playground), 3.6.4 (locally)
Search Terms:
stringifyJSON.stringify
Code
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
const result = JSON.stringify(undefined)
console.log(result) // undefined
console.log(result.length) // Uncaught TypeError: Cannot read property 'length' of undefinedExpected behavior:
Code that assumes that the result of JSON.stringify is not undefined should fail to compile.
Actual behavior:
Code that assumes that the result of JSON.stringify is not undefined compiles, but fails at runtime.
Related Issues:
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created