typescript - 使用 instanceof 时 typescript 中不需要强制转换?

标签 typescript visual-studio-code

我正在使用 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/

相关文章:

reactjs - 类型 'name' 上不存在属性 'EventTarget' - React + TypeScript

reactjs - 在模块中使用 FormattedMessage 时出错 : Error: [React Intl] Could not find required `intl` object

visual-studio-code - 我可以使用 VS Code 批量编辑多个文件吗?

c++ - 使用运算符重载运行简单示例的问题

c++ - Visual Studio Code : C/C++: Multiple definitions for a header/include file shown; how to fix?

javascript - 如何从包含字符串、对象和数组的 Javascript 对象中检索动态指定的、任意的和深度嵌套的值?

javascript - 如何跳过 CSV 中的第一行项目?

node.js - Nestjs | e2e测试| "smuggle/inject"ConfigModule 触发验证前的自定义环境变量

visual-studio - 让 Visual Studio 使用 VS 代码快捷键/键绑定(bind)

git - 为什么 git 无法识别我的本地存储库?