什么是类型体操?
类型体操是指使用 TypeScript 的高级类型系统来解决复杂类型问题的技巧。通过掌握这些技巧,我们可以写出更安全、更灵活的代码。
条件类型
条件类型是类型体操的基础,语法类似于三元表达式:
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false映射类型
映射类型允许我们基于已有类型创建新类型:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};模板字面量类型
TypeScript 4.1 引入的模板字面量类型非常强大:
type EventName = `on${Capitalize<string>}`;
type Color = 'red' | 'blue';
type Size = 'small' | 'large';
type Combination = `${Color}-${Size}`; // 'red-small' | 'red-large' | 'blue-small' | 'blue-large'实用工具类型
深层 Partial
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};提取 Promise 值类型
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type A = UnwrapPromise<Promise<string>>; // string实战案例
在实际项目中,类型体操可以帮助我们:
学习建议
总结
类型体操是 TypeScript 的进阶技能,掌握它可以让我们写出更安全、更灵活的代码。但记住,类型系统的目的是服务开发者,不要过度复杂化。