- 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 {}
function handleAnimal(animal: Animal) {
if (animal instanceof Dog) {
console.log('This is a dog');
} else {
console.log('This is some other animal');
}
}
const myDog = new Dog();
const myAnimal = new Animal();
handleAnimal(myDog);
handleAnimal(myAnimal);
- in 类型守卫:
interface Bird {
fly: () => void;
}
interface Fish {
swim: () => void;
}
function handleCreature(creature: Bird | Fish) {
if ('fly' in creature) {
creature.fly();
} else {
creature.swim();
}
}
const bird: Bird = { fly: () => console.log('Flying') };
const fish: Fish = { swim: () => console.log('Swimming') };
handleCreature(bird);
handleCreature(fish);
- 用户自定义类型守卫函数:
function isString(value: string | number): value is string {
return typeof value ==='string';
}
function processValue(value: string | number) {
if (isString(value)) {
console.log(value.length);
} else {
console.log(value.toFixed(2));
}
}
processValue('test');
processValue(42);