MST

星途 面试题库

面试题:TypeScript复杂对象结构下的类型保护函数设计

给定一个联合类型 `type Animal = { type: 'dog'; name: string; bark: () => void; } | { type: 'cat'; name: string; meow: () => void; };`,设计一个类型保护函数,接收一个 `Animal` 类型的对象,判断它是 `dog` 类型还是 `cat` 类型,并确保在类型保护后可以正确调用对应的方法(如 `dog` 的 `bark` 方法,`cat` 的 `meow` 方法)。请详细阐述函数的设计思路及类型声明的依据。
34.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 设计思路
    • 类型保护函数需要根据联合类型中对象的某个属性来判断具体的类型。在这个 Animal 联合类型中,type 属性可以作为判断依据。
    • 函数返回一个布尔值,根据判断结果来表明传入的对象是 dog 类型还是 cat 类型。
  2. 类型声明依据
    • 函数接收一个 Animal 类型的参数,因为这是要进行类型判断的对象类型。
    • 函数返回 boolean 类型,用于表示类型判断的结果。
  3. 代码实现
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';
}
  1. 使用示例
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();
}

在上述代码中,isDogisCat 函数就是类型保护函数。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 方法。