类型编程
类型收窄技巧
is 自定义类型守卫、断言函数 asserts、in 运算符收窄
类型收窄技巧
TypeScript 的类型收窄远不止 typeof——is 自定义守卫、asserts 断言函数、in 运算符都是利器。
学完本章你将: 掌握 is 自定义类型守卫、asserts 断言函数、in 收窄。
is —— 自定义类型守卫
typescript
interface Cat { meow(): void; }
interface Dog { bark(): void; }
// 返回值是 "pet is Dog"——告诉 TS:如果返回 true,pet 就是 Dog
function isDog(pet: Cat | Dog): pet is Dog {
return "bark" in pet;
}
const pet: Cat | Dog = getPet();
if (isDog(pet)) {
pet.bark(); // ✅ 自动收窄为 Dog
} else {
pet.meow(); // ✅ 自动收窄为 Cat
}
asserts —— 断言函数
typescript
// asserts 告诉 TS:如果函数正常返回,则断言成立
function assert(condition: unknown, msg?: string): asserts condition {
if (!condition) throw new Error(msg);
}
const x: unknown = 42;
assert(typeof x === "number");
x.toFixed(2); // ✅ TS 知道 x 是 number
// 实用:非空断言
function assertNotNull<T>(val: T | null): asserts val is T {
if (val === null) throw new Error("值为 null");
}
in 运算符收窄
typescript
type ApiResponse =
| { status: "ok"; data: string }
| { status: "error"; message: string };
function handle(resp: ApiResponse) {
if ("data" in resp) {
console.log(resp.data); // resp 收窄为 ok 分支
} else {
console.log(resp.message); // resp 收窄为 error 分支
}
}