TypeScript 类型保护详解
类型保护是 TypeScript 中一种用于在特定代码块中更精确地确定变量类型的机制。它允许你在条件分支中缩小变量的类型范围,从而获得更准确的类型推断和更安全的代码。
1. 为什么需要类型保护
在 TypeScript 中,联合类型非常有用,但当你需要针对不同类型执行不同操作时,就需要一种方法来区分这些类型:
function doSomething(value: string | number) {// 这里 value 可能是 string 或 number// 如何安全地使用特定类型的方法?
}
2. 类型保护的几种方式
2.1. typeof 类型保护
使用 typeof 操作符进行基本类型的区分:
function padLeft(value: string, padding: string | number) {if (typeof padding === "number") {return Array(padding + 1).join(" ") + value;}if (typeof padding === "string") {return padding + value;}throw new Error(`Expected string or number, got '${padding}'.`);
}
typeof 类型保护这些类型:"string" ,"number","bigint","boolean","symbol","undefined","object","function"
2.2. instanceof 类型保护
用于检查一个值是否是某个类的实例:
class Bird {fly() {console.log("flying");}
}class Fish {swim() {console.log("swimming");}
}function move(pet: Bird | Fish) {if (pet instanceof Bird) {pet.fly();} else {pet.swim();}
}
2.3. in 操作符类型保护
检查对象是否具有特定属性:
interface Bird {fly(): void;layEggs(): void;
}interface Fish {swim(): void;layEggs(): void;
}function move(pet: Bird | Fish) {if ("fly" in pet) {pet.fly();} else {pet.swim();}
}
2.4. 自定义类型保护(类型谓词)
通过定义一个返回类型谓词(parameterName is Type)的函数来创建自定义类型保护:
interface Cat {meow(): void;
}interface Dog {bark(): void;
}function isCat(animal: Cat | Dog): animal is Cat {return (animal as Cat).meow !== undefined;
}function handleAnimal(animal: Cat | Dog) {if (isCat(animal)) {animal.meow(); // 这里 animal 被识别为 Cat} else {animal.bark(); // 这里 animal 被识别为 Dog}
}
2.5. 可辨识联合(Discriminated Unions)
通过共同的字面量属性来区分类型:
interface Square {kind: "square";size: number;
}interface Rectangle {kind: "rectangle";width: number;height: number;
}type Shape = Square | Rectangle;function area(shape: Shape) {switch (shape.kind) {case "square":return shape.size * shape.size;case "rectangle":return shape.width * shape.height;}
}
2.6. 非空断言
使用 !
后缀表示该值不为 null 或 undefined:
function fixed(name: string | null): string {function postfix(epithet: string) {return name!.charAt(0) + '. the ' + epithet; // 使用 ! 断言 name 不为 null}name = name || "Bob";return postfix("great");
}
3. 类型保护的最佳实践
1. 优先使用内置操作符:typeof
、instanceof
和 in
是最高效的类型保护方式;
2. 复杂类型使用自定义类型保护:当内置操作符不够用时,使用类型谓词函数;
3. 设计可辨识联合:在设计类型时考虑添加公共的可辨识字段;
4. 避免过度使用非空断言:尽可能让类型系统自动推断非空状态;
4. 总结
TypeScript 的类型保护机制提供了多种方式来缩小变量类型范围,使开发者能够在特定代码块中获得更精确的类型信息。合理使用类型保护可以显著提高代码的类型安全性和可维护性。