-
Notifications
You must be signed in to change notification settings - Fork 12.4k
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
JSON.parse() returns any, but should return Object #15225
Comments
The type |
If that's the policy, fine then. IMHO if one wants ease of use, will go with JavaScript; TypeScript sounds to me like the option to chose when you want precisely type correctness. |
|
I know. I understand I was wrong on my initial suggestion, After giving it some thought, I think it is not possible to correctly represent type JsonObject =
(number | string | boolean | null | Object) | Array<
(number | string | boolean | null | Object) | Array<
(number | string | boolean | null | Object) | Array<any>>>
function parseOne(): JsonObject {
return JSON.parse('1')
}
const n: number = <number> parseOne() I wonder what is the approach taken by TypeScript in similar recursive cases (if they exist). |
Maybe export type JSONObject = { [key: string]: JSON }
export interface JSONArray extends Array<JSON> {}
export type JSON = null | string | number | boolean | JSONArray | JSONObject EDIT: TypeScript 2.2.2 |
I'm amazed that works, but with |
function doSomething(data: string): Promise<any> {
return JSON.parse(data)
}
Indeed, but if you are OK with explicitly returning |
I don't get your point, sorry. |
This issue seems to have been already addressed or is unactionable at the moment. I am auto-closing it for now. |
Hi, if I understood this issue correctly, it would be the cause for the behaviour below. Is that correct?
|
Yes. |
is it possible to create a typescript function in json?? |
TypeScript Version: 2.3.0
Expected behavior:
JSON.parse()
should returnObject
, as stated in MDN.Actual behavior:
JSON.parse()
returnsany
, essentially getting rid of the useful compile-time type checks.I realized about this while working on a project with a person new to TypeScript. She made a copy/paste mistake and ended up with a code equivalent to this:
For which TypeScript didn't show any error.
The text was updated successfully, but these errors were encountered: