TypeScript 深度类型编程
递归类型与高级类型守卫是 TypeScript 深度类型编程的基础,下面梳理核心用法。
递归类型
递归类型指类型引用自身,用于描述树形或嵌套数据结构:
TypeScript
interface TreeNode {
value: string;
children: TreeNode[];
}
const tree: TreeNode = {
value: "root",
children: [
{ value: "child1", children: [] },
{
value: "child2",
children: [
{ value: "grandchild", children: [] }
]
}
]
};
递归 JSON 类型
TypeScript
type JSONValue =
| string
| number
| boolean
| null
| { [key: string]: JSONValue }
| JSONValue[];
const data: JSONValue = {
name: "Alice",
scores: [90, 85, 92],
meta: { active: true, tags: ["admin"] }
};
递归类型别名
使用 type 递归定义复杂嵌套类型:
TypeScript
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
interface Config {
database: {
host: string;
port: number;
options: {
timeout: number;
retries: number;
};
};
}
type PartialConfig = DeepPartial<Config>;
// 所有层级都变为可选
const cfg: PartialConfig = {
database: {
options: { timeout: 5000 }
}
};
递归只读
TypeScript
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
interface State {
user: {
name: string;
prefs: {
theme: string;
};
};
}
const readonlyState: DeepReadonly<State> = {
user: { name: "Alice", prefs: { theme: "dark" } }
};
// readonlyState.user.name = "Bob"; // ❌ 无法修改
注意:TypeScript 4.1+ 支持递归条件类型,之前版本递归深度有限制。
类型守卫
高级类型守卫用于精确缩窄联合类型范围:
typeof 守卫
TypeScript
function process(val: string | number) {
if (typeof val === "string") {
val.toUpperCase(); // val 类型为 string
} else {
val.toFixed(2); // val 类型为 number
}
}
instanceof 守卫
TypeScript
class Cat { meow() {} }
class Dog { bark() {} }
function handle(animal: Cat | Dog) {
if (animal instanceof Cat) {
animal.meow(); // animal 类型为 Cat
} else {
animal.bark(); // animal 类型为 Dog
}
}
in 守卫
TypeScript
interface Bird { fly(): void; }
interface Fish { swim(): void; }
function move(pet: Bird | Fish) {
if ("fly" in pet) {
pet.fly();
} else {
pet.swim();
}
}
自定义类型守卫
TypeScript
interface Admin { role: "admin"; permissions: string[]; }
interface User { role: "user"; name: string; }
function isAdmin(person: Admin | User): person is Admin {
return person.role === "admin";
}
function handlePerson(person: Admin | User) {
if (isAdmin(person)) {
console.log(person.permissions); // person 类型为 Admin
} else {
console.log(person.name); // person 类型为 User
}
}
可辨识联合类型
TypeScript
interface Circle { kind: "circle"; radius: number; }
interface Square { kind: "square"; side: number; }
interface Rectangle { kind: "rectangle"; width: number; height: number; }
type Shape = Circle | Square | Rectangle;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
case "rectangle": return shape.width * shape.height;
}
}
要点总结
- 递归类型通过接口或 type 别名引用自身,描述树形/嵌套结构
type递归条件类型可遍历对象所有层级(如 DeepPartial/DeepReadonly)- 类型守卫
typeof/instanceof/in缩窄联合类型范围 - 自定义类型守卫用
param is Type返回值精确标注 - 可辨识联合类型通过共同字面量属性(如
kind)配合switch精确分支处理
📝 发现内容有误?点击此处直接编辑