我正在阅读Typescript手册中的User-Defined Type Guards。假设你有要缩小如下的联合类型:替代方法使用用户定义的类型警卫?
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
不打字稿已经解析,看起来像一个后卫类型的函数来实现该功能,然后缩小范围函数调用的类型?有没有其他的方式来保护警卫队?