类型检查不适用于 JSON.parse()?
Type checking doesn't work with JSON.parse()?
找不到正确的解释为什么类型检查不适用于 JSON.parse(),有人可以解释一下吗?示例:
> 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'
谢谢!
因为如果您看到 JSON.parse
的类型定义,它 returns any
:
parse(text: string, reviver?: (key: any, value: any) => any): any;
这意味着类型检查将在解析的输出上被禁用。您可以了解有关 any
type in the official documentation.
的更多信息
找不到正确的解释为什么类型检查不适用于 JSON.parse(),有人可以解释一下吗?示例:
> 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'
谢谢!
因为如果您看到 JSON.parse
的类型定义,它 returns any
:
parse(text: string, reviver?: (key: any, value: any) => any): any;
这意味着类型检查将在解析的输出上被禁用。您可以了解有关 any
type in the official documentation.