typescript类型断言

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 ((pet).swim) {
    (pet).swim()
}
else {
    (pet).fly()
}

你可能感兴趣的:(TypeScript)