|
| 1 | +// 通用工具类型 |
| 2 | + |
| 3 | +/** 允许为 null 的类型 */ |
| 4 | +export type Nullable<T> = T | null |
| 5 | + |
| 6 | +/** 允许为 undefined 的类型 */ |
| 7 | +export type Optional<T> = T | undefined |
| 8 | + |
| 9 | +/** 允许为 null 或 undefined 的类型 */ |
| 10 | +export type Maybe<T> = T | null | undefined |
| 11 | + |
| 12 | +/** 获取对象所有 value 的联合类型 */ |
| 13 | +export type ValueOf<T> = T[keyof T] |
| 14 | + |
| 15 | +/** 递归地将对象所有属性变为可选 */ |
| 16 | +export type DeepPartial<T> = { |
| 17 | + [P in keyof T]?: DeepPartial<T[P]> |
| 18 | +} |
| 19 | + |
| 20 | +/** 原始类型的联合 */ |
| 21 | +export type Primitive = |
| 22 | + | string |
| 23 | + | number |
| 24 | + | boolean |
| 25 | + | bigint |
| 26 | + | symbol |
| 27 | + | null |
| 28 | + | undefined |
| 29 | + |
| 30 | +/** 合并两个类型,U 的属性会覆盖 T 的同名属性 */ |
| 31 | +export type Merge<T, U> = Omit<T, keyof U> & U |
| 32 | + |
| 33 | +/** 从对象类型 T 中排除指定属性 K */ |
| 34 | +export type Without<T, K extends keyof T> = Omit<T, K> |
| 35 | + |
| 36 | +/** 只保留对象类型 T 的指定属性 K */ |
| 37 | +export type WithOnly<T, K extends keyof T> = Pick<T, K> |
| 38 | + |
| 39 | +/** 递归地将对象所有属性变为只读 */ |
| 40 | +export type DeepReadonly<T> = { |
| 41 | + readonly [P in keyof T]: DeepReadonly<T[P]> |
| 42 | +} |
| 43 | + |
| 44 | +/** 递归地将对象所有属性变为可选 */ |
| 45 | +export type DeepOptional<T> = { |
| 46 | + [P in keyof T]?: DeepOptional<T[P]> |
| 47 | +} |
| 48 | + |
| 49 | +/** 递归地将对象所有属性变为必选 */ |
| 50 | +export type DeepRequired<T> = { |
| 51 | + [P in keyof T]-?: DeepRequired<T[P]> |
| 52 | +} |
| 53 | + |
| 54 | +/** 递归地将对象所有属性变为可变(非 readonly) */ |
| 55 | +export type DeepMutable<T> = { |
| 56 | + -readonly [P in keyof T]: DeepMutable<T[P]> |
| 57 | +} |
| 58 | + |
| 59 | +/** 获取函数参数类型组成的元组 */ |
| 60 | +export type ArgumentsType<T extends (...args: any) => any> = T extends ( |
| 61 | + ...args: infer A |
| 62 | +) => any |
| 63 | + ? A |
| 64 | + : never |
| 65 | + |
| 66 | +/** 获取函数返回值类型 */ |
| 67 | +export type ReturnTypeOf<T extends (...args: any) => any> = T extends ( |
| 68 | + ...args: any |
| 69 | +) => infer R |
| 70 | + ? R |
| 71 | + : any |
| 72 | + |
| 73 | +/** 将联合类型转为交叉类型 */ |
| 74 | +export type UnionToIntersection<U> = ( |
| 75 | + U extends any ? (k: U) => void : never |
| 76 | +) extends (k: infer I) => void |
| 77 | + ? I |
| 78 | + : never |
| 79 | + |
| 80 | +/** 判断类型是否为 any */ |
| 81 | +export type IsAny<T> = 0 extends 1 & T ? true : false |
| 82 | + |
| 83 | +// 你可以根据需要继续添加更多类型 |
0 commit comments