TypeScript 中的 is 关键字

使用 is 关键字实现类型保护和类型收窄

问题

TypeScript 中的 is 关键字有什么用?

解答

is 关键字用于创建类型谓词函数(Type Predicate),实现类型保护。它可以在运行时判断一个对象是否属于某个类型,并让 TypeScript 在条件分支中自动收窄类型。

基本用法

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

class Dog extends Animal {
    breed: string;
    constructor(name: string, breed: string) {
        super(name);
        this.breed = breed;
    }
}

function isDog(animal: Animal): animal is Dog {
    return (animal as Dog).breed !== undefined;
}

let a1 = new Animal("Tom");
let d1 = new Dog("Tony", "Poodle");

if (isDog(d1)) {
    // TypeScript 知道这里 d1 是 Dog 类型
    console.log(d1.breed); // 可以安全访问 breed 属性
}

工作原理

isDog 函数的返回类型是 animal is Dog,这告诉 TypeScript:当函数返回 true 时,参数 animal 就是 Dog 类型。TypeScript 会在 if 语句块中自动将类型收窄为 Dog,从而可以安全访问 breed 属性。

关键点

  • is 关键字用于定义类型谓词函数,格式为 参数名 is 类型
  • 类型谓词函数返回布尔值,true 表示参数符合指定类型
  • TypeScript 会根据类型谓词的结果自动收窄类型范围
  • 常用于处理联合类型和继承关系中的类型判断