MST

星途 面试题库

面试题:TypeScript 联合类型在类型保护中的常见应用场景

请举例说明 TypeScript 联合类型在类型保护中的至少两个常见应用场景,并编写相应代码展示如何通过类型保护来处理联合类型。
29.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

场景一:函数参数为联合类型,通过 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);