Skip to content

The type definition for JSON.stringify erroneously has return type string #34630

@mpiroc

Description

@mpiroc

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:

  • stringify
  • JSON.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 undefined

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

Playground Link:
http://www.typescriptlang.org/play/?ssl=3&ssc=93&pln=3&pc=61#code/MYewdgzgLgBATgUwgVwDawLwwFIGUDyAcgHTRwCWYA5uQGYCeAFMmACYK2UKsCUAUKEghUCYqhBVGiFOh4wA9PJgt2nMNwHgIw0eMnS0UMQmpQAFnMUwAqmGABDZFTOwAKvQAOCAKJw4IOAAuGABhezAwEFhEe1YYD38vOCh6GAByEVMzNJgQWmU2Di5WIA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions