Skip to content

JSON.parse generic #44603

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

Closed
PumpedSardines opened this issue Jun 15, 2021 · 3 comments
Closed

JSON.parse generic #44603

PumpedSardines opened this issue Jun 15, 2021 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@PumpedSardines
Copy link

Suggestion

The JSON.parse function should utilize a generic.

πŸ” Search Terms

JSON parse generic

βœ… Viability Checklist

My suggestion meets these guidelines:

  • [*] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [*] This wouldn't change the runtime behavior of existing JavaScript code
  • [*] This could be implemented without emitting different JS based on the types of the expressions
  • [*] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • [*] This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Adding generics to JSON.parse

πŸ“ƒ Motivating Example

interface MyInterface {
     test: string,
    example: number
}
const myArr = JSON.parse<MyInterface[]>(fetchResponseText);

Removing refrence

interface MyInterface {
     test: string,
    example: number
}
const myOtherArr = JSON.parse<MyInterface>(JSON.stringify(myArr));

πŸ’» Use Cases

Make it easier and more convinient to parse JSON.

@nmain
Copy link

nmain commented Jun 15, 2021

I can't find a precise issue that this is a duplicate of, but similar requests have been rejected before: #44000.

Generic type parameters that only appear in the output position of functions are just assertions in disguise, so why not just write that? It only costs two characters more.

JSON.parse(s) as T
JSON.parse<T>(s)

@MartinJohns
Copy link
Contributor

This would just give people the false impression of type safety.

Instead the type should be unknown, but that was deemed a good big of a breaking change.

@MartinJohns
Copy link
Contributor

Duplicate of #30220. Used search terms: json.parse in:title

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants