function isDog(animal: Animal): animal is { type: 'dog'; name: string; bark: () => void } {
return animal.type === 'dog';
}
function handleAnimal(animal: Animal) {
if (isDog(animal)) {
animal.bark();
} else {
animal.meow();
}
}
类型保护实现原理
- 类型谓词:在
isDog
函数中,使用了类型谓词 animal is { type: 'dog'; name: string; bark: () => void }
。它的作用是告诉TypeScript编译器,当isDog
函数返回true
时,传入的animal
参数实际上就是{ type: 'dog'; name: string; bark: () => void }
类型。
- 缩小类型范围:通过
if (isDog(animal))
这样的条件判断,在if
代码块内,TypeScript会基于isDog
函数的返回值,将animal
的类型范围缩小为{ type: 'dog'; name: string; bark: () => void }
,从而可以安全地调用bark
方法。在else
代码块内,animal
的类型就被缩小为{ type: 'cat'; name: string; meow: () => void }
,可以安全调用meow
方法。这种机制使得在联合类型中能够精确地处理不同类型的对象,提高代码的类型安全性。