我试图了解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
在第3行中A
,我暗示编译器该参数是类型的,string
而显然不是。但是,TypeScript将编译该行而不会发出任何错误。
这不会在B行中发生。我传递了anumber
并暗示它是a string
。
怎么行A
不会失败编译?类型是否有特殊情况null
?
尽管进行了谷歌搜索,但我找不到令人满意的解释。欢迎提供指向资源的链接,以解释我的代码中发生的事情。
除非您启用strictNull
签入功能tsconfig.json
,否则所有类型都隐式undefined
和null
类型。因此,当您键入内容时string
,基本上就是这样string | undefined | null
。我绝对建议启用该选项,因为它会捕获很多不需要的错误。
您可以在此处了解更多信息:https : //basarat.gitbook.io/typescript/intro/strictnullchecks
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句