在TypeScript中,当调用函数时,为什么我可以提示null参数具有其他类型



我试图理解如何在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检查,否则所有类型都隐式具有undefinednull类型。所以当你输入string时,它基本上就是string | undefined | null。我绝对建议启用这个选项,因为它会捕获很多不需要的错误。

您可以在此处阅读更多信息:https://basarat.gitbook.io/typescript/intro/strictnullchecks

最新更新