文字作品文章技术教程React
理解 TypeScript 类型体操
深入理解 TypeScript 高级类型系统,从 Conditional Types 到 Template Literal Types。
2026/3/18约 3,200 字 · 阅读约 10 分钟6 次阅读
TypeScript 的类型系统是图灵完备的,这意味着理论上你可以在类型层面实现任何计算逻辑。本文将从基础到进阶,带你理解 TypeScript 的「类型体操」。
1. Conditional Types
条件类型是 TypeScript 类型体操的基石:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
2. Infer 关键字
infer 允许我们在条件类型中提取类型:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Fn = () => string;
type R = ReturnType<Fn>; // string
3. Template Literal Types
模板字面量类型让字符串操作在类型层面成为可能:
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
4. 递归类型
TypeScript 4.1+ 支持递归条件类型:
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object
? DeepReadonly<T[K]>
: T[K];
};
5. 实战:实现一个类型安全的路由系统
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractParams<Rest>]: string }
: T extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
type Params = ExtractParams<"/users/:id/posts/:postId">;
// { id: string; postId: string }
总结
掌握 TypeScript 的高级类型系统不是目的,而是手段。它帮助我们在编译时捕获更多错误,写出更安全、更可维护的代码。
记住:最好的类型是你不需要写的类型。——让 TypeScript 自己推断。