场景一:函数参数为联合类型,通过 typeof
进行类型保护
function printValue(value: string | number) {
if (typeof value ==='string') {
console.log(value.length);
} else {
console.log(value.toFixed(2));
}
}
printValue('hello');
printValue(123);
场景二:对象属性为联合类型,通过 instanceof
进行类型保护
class Animal {}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
class Cat extends Animal {
meow() {
console.log('Meow!');
}
}
function handleAnimal(animal: Animal | Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else if (animal instanceof Cat) {
animal.meow();
}
}
const myDog = new Dog();
const myCat = new Cat();
handleAnimal(myDog);
handleAnimal(myCat);
场景三:自定义类型保护函数,用于联合类型判断
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
function isBird(pet: Bird | Fish): pet is Bird {
return (pet as Bird).fly!== undefined;
}
function handlePet(pet: Bird | Fish) {
if (isBird(pet)) {
pet.fly();
} else {
pet.swim();
}
pet.layEggs();
}
const bird: Bird = {
fly() {
console.log('Flying...');
},
layEggs() {
console.log('Laying eggs...');
}
};
const fish: Fish = {
swim() {
console.log('Swimming...');
},
layEggs() {
console.log('Laying eggs...');
}
};
handlePet(bird);
handlePet(fish);