javascript - 在 Typescript 的类型注释中使用 'is' 关键字的目的是什么

标签 javascript typescript

我正在读一本 Typescript 书,看到了一些像这样的代码:

class Product {
   ...
}

function Test(args): args is Product {
   return args instanceof Product;
}

但是函数的返回类型不是boolean吗?所以我们可以写一个普通的函数:

function Test(args): boolean {
   return args instanceof Product;
}

使用返回类型注解为 args is XXX 有什么好处?而不是简单的boolean

最佳答案

您正在描述使用 user-defined type guard .

文档中的示例说明了如何通过缩小联合类型来发挥作用。

function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

如果定义了 swim,代码的任何条件分支都会将类型缩小为 Fish

if (isFish(pet)) {
    pet.swim(); // compiler knows that `pet` is of the `Fish` type
}

关于javascript - 在 Typescript 的类型注释中使用 'is' 关键字的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072117/

相关文章:

javascript - 如果使用 then ,是否需要在 Promise 中嵌套 catch?

javascript - 在下拉列表中选择值时使用 ajax 发布 MVC 值

JavaScript "cache"与 "memory"

javascript - Jquery Tools 可滚动 onBeforeSeek 函数然后滑动到下一个

angular - 在 ng2-chart 中设置条形图的颜色

typescript - 更好的 TypeScript 推断可以返回多个不同对象的函数的返回类型

typescript - 多层式防护罩

javascript - 谷歌浏览器中按钮标签的子节点如何触发 onclick 事件?

javascript - 具有多个参数的 Ramda 管道

reactjs - 使用两个不同的 prop 接口(interface) React TypeScript 组件