我正在使用 instanceof
来检查对象是否属于某种类型。
我希望如果这是真的,我仍然需要将该对象转换为特定类型才能使用它。
但是,在 IF 语句内部似乎不需要强制转换。至少在 Visual Studio Code 和 Typescript Playground 中没有.
class Drink {
price: number = 4;
}
class Beer extends Drink {
alcohol: number = 6;
}
let array: Array<Drink> = new Array<Drink>();
array.push(new Drink(), new Beer(), new Drink());
for (let g of array) {
// here, only 'price' is available as a property of drink
console.log(g.price);
if (g instanceof Beer) {
// but unexpectedly, inside the IF statement
// the alcohol value IS available!
console.log(g.alcohol);
// I expected I needed to cast drink to beer first:
console.log((<Beer>g).alcohol);
}
}
这是 Typescript 编辑器非常聪明的行为还是一个小故障?
复制>将以上代码粘贴到Typescript Playground看到这种行为......
最佳答案
据我所知这是Type Guards , 自 v1.4 起可用:
Type Guards
A common pattern in JavaScript is to use typeof or instanceof to examine the type of an expression at runtime. TypeScript now understands these conditions and will change type inference accordingly when used in an if block.
关于typescript - 使用 instanceof 时 typescript 中不需要强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138189/