我正在读一本 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/