MST

星途 面试题库

面试题:TypeScript中类型保护的常见方法有哪些

请列举TypeScript中至少三种常见的类型保护方法,并分别用代码示例说明如何使用它们来缩小类型范围。
17.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. typeof 类型保护
    • 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 类型保护
    • instanceof 用于检查一个对象是否是某个类的实例,在面向对象编程中可缩小类型范围。
    • 示例代码:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

function handleAnimal(animal: Animal) {
    if (animal instanceof Dog) {
        console.log('This is a dog');
    } else if (animal instanceof Cat) {
        console.log('This is a cat');
    }
}

const dog = new Dog();
const cat = new Cat();
handleAnimal(dog);
handleAnimal(cat);
  1. in 类型保护
    • in 操作符用于检查对象中是否包含某个属性,以此来缩小类型范围。
    • 示例代码:
interface HasName {
    name: string;
}
interface HasAge {
    age: number;
}

function printInfo(person: HasName | HasAge) {
    if ('name' in person) {
        console.log(`Name: ${person.name}`);
    } else if ('age' in person) {
        console.log(`Age: ${person.age}`);
    }
}

const person1: HasName = { name: 'Alice' };
const person2: HasAge = { age: 30 };
printInfo(person1);
printInfo(person2);
  1. 自定义类型保护函数
    • 可以通过自定义函数来实现类型保护,函数返回一个类型谓词。
    • 示例代码:
function isString(value: any): value is string {
    return typeof value ==='string';
}

function processValue(value: string | number) {
    if (isString(value)) {
        console.log(value.toUpperCase());
    } else {
        console.log(value * 2);
    }
}

processValue('world');
processValue(42);