【发布时间】:2017-06-27 08:00:04
【问题描述】:
我正在阅读 Typescript 手册中有关用户定义类型保护的内容。假设您有一个想要缩小范围的联合类型,如下所示:
interface Bird{
fly();
layEggs();
}
interface Fish{
swim();
layEggs();
}
class SmallPet implements Fish,Bird{
constructor(){
}
fly() { console.log("fly")};
swim() { console.log("swim")};
layEggs() {console.log("laying eggs") };
}
function getSmallPet(): Fish | Bird{
return new SmallPet();
}
function isFish(pet: Fish | Bird): pet is Fish{
return (<Fish>pet).swim !== undefined;
}
let pet = getSmallPet();
if (isFish(pet))
pet.swim(); //works
函数 isFish 是手册中提到的用户定义的类型保护。我的问题是这是如何工作的?我试图以更草率的方式实现相同的结果,但这显然不会奏效:
pet is Fish;
pet.swim(); //doesn't work
Typescript 是否必须解析一个看起来像类型保护的函数才能实现此功能并随后通过函数调用缩小类型?没有其他方法可以使用类型保护吗?
【问题讨论】:
标签: typescript