Skip to content

JSON.stringify(undefined) incorrectly types the return value as stringΒ #62838

@afgomez

Description

@afgomez

πŸ”Ž Search Terms

"JSON.stringify()"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "JSON.stringify()`

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAZiEMC8MBSBlA8gOQHTQBOAlmAObFwCeAFAK5gAmApnKc4wJQDcAUAiAJQAhoSgQA6sSgALGgCIAkgHIAtjGCFhEGaTIxwMQgyjFVzADQw6iEDIOJ7tmfJ5A

πŸ’» Code

const foo = JSON.stringify(undefined);
foo.startsWith("I'm crashing on runtime, uoooh oooh oooh");

πŸ™ Actual behavior

The foo variable is typed as string

πŸ™‚ Expected behavior

the foo variable is typed as undefined

Additional information about the issue

I think this should be relatively easy to fix with the following overload

interface JSON {
    // ...
    stringify(value: undefined, replacer?: (number | string)[] | null, space?: string | number): undefined;
}

But such a change will probably start throwing compilation errors in the wild.

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