typescript编程离不开类型工具的帮助,类型工具就是类型版的lodash
工具类型的设计
泛型, TS的类型中能作为类型入口的只有泛型
// 比如Partial, 它的作用是将属性全部变为可选
type Partial<T> = { [P in keyof T]?: T[P] }
// 在这个工具类型中,需要将类型通过泛型T传入才能对类型进行处理并返回新类型
// 一切工具类型的基础就是泛型
类型递归,在类型中也有类似于js递归的操作,上面提到的Partial可以把属性变为可选,但是他的问题是无法把深层属性变成可选,只能处理外层属性 ```typescript interface Company { id: number name: string } interface Person { id: number name: string address: string compant: Company }
type R1 = Partial
// 处理深层属性,就必须要到类型递归
type DeepPartial
type R2 = DeepPartial
3. 关键字,
1. keyof,
1. typeof ,
1. + -这两个关键字用于给映射类型中的属性添加修饰符,
1. -?就代表将可选属性变为必选属性
1. -readonly代表将只读属性变为非只读
```typescript
// Required<T>类型,将传入的属性变为必选项
type Required<T> = { [P in keyof T]-?: T[P] }
- 常见工具类型的解读
- Exclude, Exclude的作用是从T中排除可分配给U的元素
- Omit, Omit = Exclude + Pick, 作用是忽略T中的某些属性
- Merge, 将两个对象的属性进行合并
- Intersection, 是取T的属性,此属性同样也存在于U
- Overwrite, 是用U的属性覆盖T的相同属性
- Mutable, 将T的所用属性的readonly移除
```typescript
type Exclude
= T extends U ? never: T; type T = Exclude<1|2, 1|3> // 2;
// Omit = Exclude + Pick
type Omit
// Merge
type Intersection
type Diff
= Pick
type Mutable
小结
- 泛型,类型工具设计的基础
- 类型递归
- 常见类型工具的实现
- utility-types, 工具类型通用库,https://github.com/piotrwitek/utility-types