这类似于 #40796374 ,但这是围绕类型,而我正在使用接口。
鉴于以下代码:
interface Foo {
name: string;
}
function go() {
let instance: Foo | null = null;
let mutator = () => {
instance = {
name: 'string'
};
};
mutator();
if (instance == null) {
console.log('Instance is null or undefined');
} else {
console.log(instance.name);
}
}
我有一个错误,说“从不”类型上不存在“属性”名称。
我不明白实例怎么可能是“从不”。任何人都可以对此有所了解吗?
原文由 Ray Booysen 发布,翻译遵循 CC BY-SA 4.0 许可协议
因为您将
instance
分配给null
。编译器推断它永远不会是null
以外的任何东西。所以它假定 else 块永远不应该被执行,所以instance
never
。现在,如果您不将其声明为文字值
null
,并通过任何其他方式获取它(例如:let instance: Foo | null = getFoo();
),您将看到instance
将是null
在 if 块内和Foo
在 else 块内。从不输入文档: https ://www.typescriptlang.org/docs/handbook/basic-types.html#never
编辑:
更新示例中的问题实际上是编译器的一个未解决问题。看:
https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176