saza
saza

Reputation: 588

Type checking doesn't work with JSON.parse()?

couldn't find a proper explanation why type checking doesn't work with JSON.parse(), can someone shed some light on it? Example:

> let n: number = 1
undefined
> typeof n
'number'
> n = true
⨯ Unable to compile TypeScript: [eval].ts (1,1): Type 'true' is not assignable to type 'number'. (2322)
> typeof JSON.parse(JSON.stringify(true))
'boolean'
> n = JSON.parse(JSON.stringify(true))
true
> typeof n
'boolean'

Thanks!

Upvotes: 0

Views: 528

Answers (1)

Saravana
Saravana

Reputation: 40534

Because if you see the type definition for JSON.parse, it returns any:

parse(text: string, reviver?: (key: any, value: any) => any): any;

Which means that type checking will be disabled on the parsed output. You can learn more about the any type in the official documentation.

Upvotes: 3

Related Questions