TypeScript in操作符缩小
语法:
"valuse" in x
实例:
type Fish = { swim: () => void }
type Bird = { fly: () => void }
type Human = { swim?: () => void; fly?: () => void }
type Animal = Fish | Bird | Human
function move(animal: Animal) {
if ("swim" in animal) {
// animal: Fish | Human
return (animal as Fish).swim();
}
return (animal as Bird).fly();
}
网友评论