打字稿推断错误的类型
我希望“某些东西”会有一种"string |null"
,但vscode会给"string"
代替
我正在使用打字稿3.3
interface S {
// wrong expectation : "something" has type of string
something : string | null
}
因为它是由定义。
默认情况下,null和undefined是所有其他类型的子类型。这意味着您可以将null和undefined分配给数字之类的东西。
https://www.typescriptlang.org/docs/handbook/basic-types.html
感谢@Nail Achmedzhanov根据原始问题发表的评论。
这是因为“null strict checks”设置为false。
设置为true应该可以解决我的问题。 (找到覆盖react-native typescript设置的方法)
{
"compilerOptions": {
"strictNullChecks": true, /* Enable strict null checks. */
}