面试题答案
一键面试- 设计思路:
- 类型保护函数需要根据联合类型中对象的某个属性来判断具体的类型。在这个
Animal
联合类型中,type
属性可以作为判断依据。 - 函数返回一个布尔值,根据判断结果来表明传入的对象是
dog
类型还是cat
类型。
- 类型保护函数需要根据联合类型中对象的某个属性来判断具体的类型。在这个
- 类型声明依据:
- 函数接收一个
Animal
类型的参数,因为这是要进行类型判断的对象类型。 - 函数返回
boolean
类型,用于表示类型判断的结果。
- 函数接收一个
- 代码实现:
type Animal = { type: 'dog'; name: string; bark: () => void; } | { type: 'cat'; name: string; meow: () => void; };
function isDog(animal: Animal): animal is { type: 'dog'; name: string; bark: () => void; } {
return animal.type === 'dog';
}
function isCat(animal: Animal): animal is { type: 'cat'; name: string; meow: () => void; } {
return animal.type === 'cat';
}
- 使用示例:
const myDog: Animal = { type: 'dog', name: 'Buddy', bark: () => console.log('Woof!') };
const myCat: Animal = { type: 'cat', name: 'Whiskers', meow: () => console.log('Meow!') };
if (isDog(myDog)) {
myDog.bark();
}
if (isCat(myCat)) {
myCat.meow();
}
在上述代码中,isDog
和 isCat
函数就是类型保护函数。isDog
函数通过判断 animal.type
是否为 'dog'
来确定传入的 animal
是否为 dog
类型,返回值类型使用 animal is { type: 'dog'; name: string; bark: () => void; }
,这种语法在 TypeScript 中用于类型保护,使得在通过 isDog
判断后,myDog
的类型可以被细化为 { type: 'dog'; name: string; bark: () => void; }
,从而可以安全地调用 bark
方法。同理,isCat
函数用于判断 animal
是否为 cat
类型,并在判断通过后可以安全调用 meow
方法。