我试图理解如何在TypeScript中的A
行编译,而B
行则不编译。
function someFunction<T>(arg: T): void {
console.log(arg)
}
someFunction<string>('some string') // obviously, it works
someFunction<string>(null) // [A] compiles
someFunction<string>(2) // [B] doesn't compile
在第A
行中,我暗示编译器该参数的类型为string
,而它显然不是。然而,TypeScript将编译该行而不会发出任何错误。
这在B行中没有发生。我传递一个number
,并暗示它是string
。
为什么A
行编译不失败?null
型有特殊情况吗?
尽管我在谷歌上搜索,但我找不到一个令人满意的解释。提供资源链接来解释我的代码中发生了什么是非常受欢迎的。
除非在tsconfig.json
中启用strictNull
检查,否则所有类型都隐式具有undefined
和null
类型。所以当你输入string
时,它基本上就是string | undefined | null
。我绝对建议启用这个选项,因为它会捕获很多不需要的错误。
您可以在此处阅读更多信息:https://basarat.gitbook.io/typescript/intro/strictnullchecks