【发布时间】:2017-10-24 04:21:27
【问题描述】:
这类似于#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);
}
}
我有一个错误提示“从不”类型上不存在“属性”名称。
我不明白实例怎么可能是“从不”。任何人都可以对此有所了解吗?
【问题讨论】:
-
从您的代码中可以清楚地看出,
else确实永远不会得到评估。编译器足够聪明,可以看到它。 -
这是一个例子,让我再添加一些代码表明它仍然存在问题。
-
It's pretty clear from your code that the else would indeed never get evaluated.这一点都不明显,也没有智能编译器。有一个愚蠢的转译器,它偏离了既定的做法。例如,在 C# 中,可以将null分配给任何对象... -
@BozhidarStoyneff,这是成立但遗憾的做法:en.wikipedia.org/wiki/Null_pointer#History
-
当与 try catch finally 变量一起使用时,这将成为一个严重的头痛问题,这些变量需要在 finally 块中处理..
标签: typescript