MST

星途 面试题库

面试题:TypeScript中类型收缩的常见方式有哪些

请列举至少三种TypeScript中实现类型收缩的常见方式,并各举一个简单代码示例说明。
47.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. typeof 类型守卫
    • 在运行时检查变量的类型。
    • 示例:
function printValue(value: string | number) {
    if (typeof value ==='string') {
        console.log(value.length);
    } else {
        console.log(value.toFixed(2));
    }
}
printValue('hello');
printValue(123);
  1. 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);
  1. 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);
  1. 用户自定义类型守卫函数
    • 通过返回类型谓词来实现类型收缩。
    • 示例:
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);