TypeScript版本3.0.1
请看这个样本:
class Bar{
public id ='bar';
}
function createABar():Bar|Error{
return new Bar();
}
function check(){
let aGlobal = createABar();
if (aGlobal instanceof Bar){
let aGlobal2=aGlobal;
let arr=['one', 'bar', 'three'];
let theAGlobalId=aGlobal.id; // ts no complaints
let exists = arr.find(i => i == aGlobal.id); // ts Property 'id' does not exist on type 'Bar | Error'.
console.log(exists); // it has been found (as expected)
// alternate syntax:
let exists2 = arr.find(function (i){return i == aGlobal.id}); // ts Property 'id' does not exist on type 'Bar | Error'.
let exists3 = arr.find(i => i == aGlobal2.id); // ts no complaints
}
}
check();
我收到错误'属性'id'在类型'Bar |上不存在错误'。'当在find的回调中访问类Bar时的id。
看起来在这种情况下,型号后卫失去了效力。
将“typeguarded”变量分配给另一个(aGlobal2)可以正常工作
这是预期的吗?
顺便说一句,我不能在这个问题中使用标签typeguard(它不存在,如果它被创建,我没有声誉来创建它?)
通常,类型保护和流量分析不跨越功能边界。在您的情况下,您传递给find
的匿名函数将不会受益于任何已完成的守卫。使用局部变量的解决方案可能是最简单和最安全的。