typescript编程离不开类型工具的帮助,类型工具就是类型版的lodash

工具类型的设计

  1. 泛型, TS的类型中能作为类型入口的只有泛型

    1. // 比如Partial, 它的作用是将属性全部变为可选
    2. type Partial<T> = { [P in keyof T]?: T[P] }
    3. // 在这个工具类型中,需要将类型通过泛型T传入才能对类型进行处理并返回新类型
    4. // 一切工具类型的基础就是泛型
  2. 类型递归,在类型中也有类似于js递归的操作,上面提到的Partial可以把属性变为可选,但是他的问题是无法把深层属性变成可选,只能处理外层属性 ```typescript interface Company { id: number name: string } interface Person { id: number name: string address: string compant: Company }

type R1 = Partial

// 处理深层属性,就必须要到类型递归 type DeepPartial = { [U in keyof T]?: T[U] extends object ? DeepPartial : T[U] }

type R2 = DeepPartial

  1. 3. 关键字,
  2. 1. keyof,
  3. 1. typeof ,
  4. 1. + -这两个关键字用于给映射类型中的属性添加修饰符,
  5. 1. -?就代表将可选属性变为必选属性
  6. 1. -readonly代表将只读属性变为非只读
  7. ```typescript
  8. // Required<T>类型,将传入的属性变为必选项
  9. type Required<T> = { [P in keyof T]-?: T[P] }
  1. 常见工具类型的解读
    1. Exclude, Exclude的作用是从T中排除可分配给U的元素
    2. Omit, Omit = Exclude + Pick, 作用是忽略T中的某些属性
    3. Merge, 将两个对象的属性进行合并
    4. Intersection, 是取T的属性,此属性同样也存在于U
    5. Overwrite, 是用U的属性覆盖T的相同属性
    6. Mutable, 将T的所用属性的readonly移除 ```typescript type Exclude = T extends U ? never: T; type T = Exclude<1|2, 1|3> // 2;

// Omit = Exclude + Pick type Omit = Pick>

// Merge = Compute + Omit // compute 是将交叉类型进行合并 type Compute = A extends Function ? A : { [K in keyof A]: A[K] } type R1 = Compute<{x: ‘x’} & {y: ‘y’}> // {x: ‘x’, y: ‘y’} type Merge = Compute>

type Intersection = Pick< T, Extract & Extract >

type Diff = T extends U ? never: T type Overwrite< T extends object, U extends object, I = Diff & Intersection

= Pick

type Mutable = { -readonly [P in keyof T]: T[P] } ```

小结

  1. 泛型,类型工具设计的基础
  2. 类型递归
  3. 常见类型工具的实现
  4. utility-types, 工具类型通用库,https://github.com/piotrwitek/utility-types