工具类型:用法与实现
工具类型用于转换已有类型。属性修饰和选择主要依赖映射类型,联合成员过滤及结构提取则依赖条件类型和 infer。
基础语法
keyof T:取得属性键的联合类型,可能包含字符串、数字和 symbol。T[K]:取得属性K的值类型。[K in keyof T]:遍历属性,即映射类型。?、-?、readonly、-readonly:添加或移除属性修饰符。T extends U ? X : Y、infer:判断兼容关系并提取类型,详见 条件类型与 infer。
下文使用同一个业务类型:
interface User {
readonly id: number;
name: string;
age?: number;
}
属性修饰
type UserPatch = Partial<User>; // 所有属性可选
type CompleteUser = Required<User>; // 所有属性必选
type ReadonlyUser = Readonly<User>; // 所有属性只读
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// 自定义类型,移除只读修饰符
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
这些转换只处理第一层属性,不会递归处理嵌套对象,也不会在运行时冻结或修改对象。
对普通嵌套数据可定义递归版本:
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
此版本保留函数类型,递归处理对象属性;它不能阻止 Map.set()、Date.setTime() 等方法修改内部状态,不适合作为所有对象的通用不可变方案。
属性选择与字典结构
type UserSummary = Pick<User, 'id' | 'name'>;
type UserWithoutId = Omit<User, 'id'>;
type Permissions = Record<'admin' | 'user', string[]>;
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyOmit<T, K extends PropertyKey> = Pick<T, Exclude<keyof T, K>>;
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };
Pick 选取属性,Omit 排除属性,Record 创建键值结构。PropertyKey 等价于 string | number | symbol;前两者会保留被选中属性原有的可选、只读修饰符。
联合类型成员过滤
type WithoutA = Exclude<'a' | 'b' | 'c', 'a'>; // 'b' | 'c'
type TextMembers = Extract<'a' | 'b' | 1, string>; // 'a' | 'b'
type NotNull = NonNullable<string | null | undefined>; // string
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type MyNonNullable<T> = T & {};
Exclude 排除可赋给 U 的成员,Extract 保留可赋给 U 的成员。在严格空值检查下,T & {} 可过滤 null、undefined。
Extract<A, B> 按可赋值关系过滤 A 的联合成员,与交叉类型 A & B 的语义不同。
函数与构造函数结构提取
type Fn = (name: string, age: number) => boolean;
type Args = Parameters<Fn>; // [name: string, age: number]
type Result = ReturnType<Fn>; // boolean
class Account {
constructor(public id: number, public name: string) {}
}
type ConstructorArgs = ConstructorParameters<typeof Account>;
// [id: number, name: string]
type AccountInstance = InstanceType<typeof Account>; // Account
以下简化实现展示 infer 如何提取结构;实际使用优先选择内置类型:
type AnyFunction = (...args: any[]) => any;
type AnyConstructor = abstract new (...args: any[]) => any;
type MyParameters<T extends AnyFunction> =
T extends (...args: infer P) => any ? P : never;
type MyReturnType<T extends AnyFunction> =
T extends (...args: any[]) => infer R ? R : never;
type MyConstructorParameters<T extends AnyConstructor> =
T extends abstract new (...args: infer P) => any ? P : never;
type MyInstanceType<T extends AnyConstructor> =
T extends abstract new (...args: any[]) => infer R ? R : never;
对重载函数或构造函数,内置提取类型以最后一个签名为准。
异步结果提取
type AsyncResult = Awaited<Promise<Promise<number>>>; // number
async function loadUser(): Promise<User> {
return { id: 1, name: 'Alice' };
}
type LoadedUser = Awaited<ReturnType<typeof loadUser>>; // User
Awaited 模拟 await 对异步结果的递归解包,比仅匹配 Promise<infer T> 更完整。
自定义联合成员运算
下面用可赋值关系类比集合运算;对于对象类型,它们不等同于按对象属性做交集或合并。
type Union<A, B> = A | B;
type Difference<A, B> = Exclude<A, B>;
type Intersection<A, B> = Extract<A, B>;
type SymmetricDifference<A, B> = Exclude<A | B, Extract<A, B>>;
type Complement<All, A extends All> = Exclude<All, A>;
type A = 'a' | 'b';
type B = 'b' | 'c';
type U = Union<A, B>; // 'a' | 'b' | 'c'
type D = Difference<A, B>; // 'a'
type I = Intersection<A, B>; // 'b'
type S = SymmetricDifference<A, B>; // 'a' | 'c'
type C = Complement<'a' | 'b' | 'c', A>; // 'c'
组合工具类型
只调整指定属性的可选性,其他属性保留原有修饰符:
type OptionalProperty<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type RequiredProperty<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
type OptionalName = OptionalProperty<User, 'name'>;
type RequiredAge = RequiredProperty<User, 'age'>;
如果要合并对象类型,并让右侧同名属性覆盖左侧,可以定义:
type Overwrite<A, B> = Omit<A, keyof B> & B;
type Merge<A, B> = Overwrite<A, B>;
type UpdatedUser = Overwrite<User, { id: string }>;
// { id: string; name: string; age?: number }
Merge、Overwrite 都不是 TypeScript 内置类型,具体语义由实现决定。直接写 A & B 不会覆盖冲突属性,而是要求同时满足两侧类型。