版权声明:17602128911 https://blog.csdn.net/bus_lupe/article/details/86500512
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function getSmallPet():Fish | Bird{
return
}
let pet = getSmallPet()
// 如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有成员
pet.layEggs()
// 每一个成员访问都会报错
// if (pet.swim) {
// pet.swim
// }
// else if (pet.fly) {
// pet.fly()
// }
// 为了让这段代码工作,我们需要使用类型断言
if ((<Fish>pet).swim) {
(<Fish>pet).swim()
}
else {
(<Bird>pet).fly()
}