类型推断

如果没有给声明的变量指定类型,TypeScript 会根据一些规则给变量推断一个类型。如:

  1. let a = 1;
  2. a = '';

上述代码会报错 Type 'string' is not assignable to type 'number'. 实际上上述等价于下面的代码:

  1. let a: nubmer = 1;
  2. a = '';

从右向左

  • 变量的类型可以由定义推断
  • 这是一个从右向左流动类型的示例

    1. let a = 1;

    可以看到
    image.png
    如果我们给变量 a 赋值其他类型会报错

    1. // Type 'string' is not assignable to type 'number'.
    2. a = '';

    底部流出

  • 返回类型能被 return 语句推断

    1. function sum(a: number, b: number) {
    2. return a + b;
    3. }
    4. const res = sum(1, 2);

    image.png

  • 尽管 TypeScript 一般情况下能推断函数的返回值,但是它可能并不是你想要的 ```typescript function addOne(a:any) { return a + 1; // 返回 any 类型 } function sum(a: number, b: number) { return a + addOne(b); // 一个数加一个 any 类型,结果也是 any 类型 }

type Ret = ReturnType; // type Ret = any

  1. <a name="J7LEu"></a>
  2. ## 结构化
  3. - 推断规则也适用于结构化的存在(对象字面量)
  4. ```typescript
  5. const person = {
  6. name: 'zhufeng'
  7. };
  8. let name = person.name;
  9. // Type 'number' is not assignable to type 'string'.
  10. name = 1;

推断规则也适用于解构

  1. const person = {
  2. name: 'f'
  3. };
  4. let { name } = person;
  5. // Type 'number' is not assignable to type 'string'.
  6. name = 1;

DefaultProps

  1. interface Person {
  2. name?: string,
  3. age?: number
  4. }
  5. const p1: Person = {
  6. name: 'f',
  7. age: 18
  8. };
  9. const p2 = {
  10. ...p1,
  11. gender: 1
  12. };
  13. type P = typeof p2;
  14. /*
  15. type P = {
  16. gender: number;
  17. name?: string | undefined;
  18. age?: number | undefined;
  19. }
  20. */

交叉类型

  • 交叉类型(Intersection Types)是将多个类型合并为一个类型
  • 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性 ```typescript interface A { name: string; age: number; } interface B { gender: number; }

type C = A & B; // person 需要具有 A 和 B 所有的属性才行 const person: C = { name: ‘f’, age: 18, gender: 1 };

type D = number | string | boolean; type E = number; type F = D & E; // f 只能赋值 number 类型 const f:F = 1;

  1. 上面的例子中给 `person` `f` 的赋值是不是和你想的不一样呢?
  2. ```typescript
  3. interface A {
  4. name: string;
  5. age: number;
  6. }
  7. interface B {
  8. gender: number;
  9. }
  10. type C = A | B;
  11. // person 只要包含 A 或者 B 中的任意属性即可,全部包含也行
  12. // const person: C = { gender: 1 };
  13. // const person: C = { name: 'f', age: 18 };
  14. // const person: C = { name: 'f', age: 18, gender: 1 };
  15. type D = number | string | boolean;
  16. type E = number;
  17. type F = D | E;
  18. // f 可以赋值为 number、string、boolean 中的任意类型
  19. // const f: F = 1;
  20. // const f: F = '';
  21. // const f: F = true;

看一下下面的代码我们应该怎么给 ab 赋值呢?

  1. interface A {
  2. a: string | number,
  3. b: string
  4. }
  5. interface B {
  6. a: number | boolean,
  7. c: string
  8. }
  9. type AB = A & B;
  10. let ab: AB =

答案如下:

  1. let ab: AB = {a: 1, b: '', c: ''};

mixin 混入模式可以让你从两个对象中创建一个新对象,新对象会拥有着两个对象所有的功能

  1. interface Person {
  2. [prop: string]: any
  3. }
  4. function mixin<T extends Person, U extends Person>(one: T, two: U): T & U {
  5. // Type '{}' is not assignable to type 'T & U'.
  6. const res = <T & U>{};
  7. for (const key in one) {
  8. (<T>res)[key] = one[key];
  9. }
  10. for (const key in two) {
  11. (<U>res)[key] = two[key];
  12. }
  13. return res;
  14. }
  15. const person = mixin({ name: 'f' }, { age: 18 });
  16. /*
  17. person: {
  18. name: string;
  19. } & {
  20. age: number;
  21. }
  22. */
  23. console.log(person.name, person.age);

可能你看到上面代码中的 (T)res[key] 感觉有点陌生,这是干啥的?实际它就是个类型断言:

  1. let a: number = 1;
  2. // Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  3. // (<string>a) = '';
  4. (<string>(<unknown>a)) = ''
  5. // 和上面的代码等价,都是断言
  6. (a as unknown as string) = ''

这里说句题外话,在 TS 中我们怎么给一个对象赋值呢?

  1. const person = {};
  2. person.name = 'f';

上述代码会报错 Property 'name' does not exist on type '{}'. 那我们应该怎么办呢?我们可以像下面这样:

  1. interface Person {
  2. [prop: string]: any
  3. }
  4. const person: Person = {};
  5. person.name = 'f';

typeof

可以获取一个变量的类型

  1. let person = {
  2. name: 'f',
  3. age: 18
  4. }
  5. type P = typeof person;
  6. /*
  7. type P = {
  8. name: string;
  9. age: number;
  10. }
  11. */

索引访问操作符

  • 可以通过[]获取一个类型的子类型 ```typescript interface Person { name: string, age: number, jobInfo: { name: string, money: number }, // interests 是一个数组,数组里面的每一项是一个包含 name 属性的对象 interests: {name:string}[] }

const jobInfo: Person[‘jobInfo’] = { name: ‘f’, money: 10000 }; const interestsName: Person[‘interests’][0][‘name’] = ‘’;

  1. <a name="EI09d"></a>
  2. # keyof
  3. - 索引类型查询操作符
  4. ```typescript
  5. interface Person {
  6. name: string,
  7. age: number
  8. }
  9. type P = keyof Person;
  10. function getName(p: Person, key: P) {
  11. return p.name;
  12. }
  13. getName({name: 'f', age:18}, 'name');

映射类型

  • 在定义的时候用in操作符去批量定义类型中的属性 ```typescript interface Person { name: string, age: number, gender: number }

type P = {

  1. [key in keyof Person]: Person[key]

}; / type P = { name: string; age: number; gender: number; } /

  1. <a name="Y5fGv"></a>
  2. ## Partial
  3. Partial 将传入的属性变为可选项
  4. ```typescript
  5. interface Person {
  6. name: string,
  7. age: number,
  8. gender: number
  9. }
  10. type P = Partial<Person>;

可以看到结果如下:
image.png
如果我们不使用 Partial 怎么将属性转为可选项呢?我们可以使用下面的方法:

  1. type P = {
  2. [key in keyof Person]?: Person[key]
  3. }

Partial 的源码

  1. type Partial<T> = {
  2. [key in keyof T]?: T[key]
  3. }

条件类型

  • 在定义泛型的时候能够添加进逻辑分支,以后泛型更加灵活

    定义条件类型

    ```typescript interface Man { name: string } interface Woman { age: number } interface Earn {} interface TubeMoney { money: number }

type Condition = T extends Man ? Earn : TubeMoney; const condition: Condition = {money: 1};

  1. <a name="ckpbb"></a>
  2. ## 条件类型的分发
  3. ```typescript
  4. interface Man {
  5. name: string
  6. }
  7. interface Woman {
  8. age: number
  9. }
  10. interface Earn {
  11. skills: Array<string>
  12. }
  13. interface TubeMoney {
  14. money: number
  15. }
  16. type Condition<T> = T extends Man ? Earn : TubeMoney;
  17. const condition1: Condition<Woman | Man> = {money: 1}; // condition1: Earn | TubeMoney
  18. const condition2: Condition<Woman | Man> = { skills: ['编程', '开车'] }; // condition2: Earn | TubeMoney
  19. const condition3: Condition<Woman> = { money: 1 }; // condition3: TubeMoney
  20. const condition4: Condition<Man> = {skills: []} // condition3
  1. type Filter<T, U> = T extends U ? T : never;
  2. type R = Filter<string|number|boolean, boolean> // R = boolean

条件类型有一个特性,就是「分布式有条件类型」,但是分布式有条件类型是有前提的,条件类型里待检查的类型必须是naked type parameter。我们把上面的例子做个修改:

  1. // T 必须是裸类型,不能有任何包含或者其他
  2. type Condition<T> = T[] extends Man[] ? Earn : TubeMoney;
  3. let condition: Condition<Woman[] | Man[]>; // condition: TubeMoney

下面这样写是没有问题的:

  1. type Condition<T> = T extends Man[] ? Earn : TubeMoney;
  2. let condition: Condition<Woman[] | Man[]>; // condition: Earn | TubeMoney

内置条件类型

TS 在内置了一些常用的条件类型,可以在 lib.es5.d.ts 中查看:
utility-types

Exclude

  • 从 T 可分配给的类型中排除 U

    1. type Exclude<T, U> = T extends U ? never : T;
    2. type R = Exclude<string | number | boolean, boolean>;
    3. /*
    4. type R = string | number
    5. */

    Extract

  • 从T中抽出可分配给U的属性构成新的类型

    1. type Extract<T, U> = T extends U ? T : never;
    2. type R = Extract<string | number | boolean, boolean>;
    3. /*
    4. type R = boolean
    5. */

    NonNullable

  • 从 T 中排除 null 和 undefined

    1. type NonNullable<T> = T extends null | undefined ? never : T;
    2. type R = NonNullable<string | null | undefined>;
    3. /*
    4. type R = string
    5. */

    ReturnType

    infer最早出现在此 PR 中,表示在 extends 条件语句中待推断的类型变量
    获取函数类型的返回类型

    1. type Exclude<T, U> = T extends U ? never : T;
    2. type R = Exclude<string | number | boolean, boolean>;
    3. /*
    4. type R = string | number
    5. */

    Parameters

    可以通过 Parameters 获取一个参数的列表 ```typescript type Parameters any> = T extends (…args: infer P) => any ? P : never;

function sum(a: number, b: number) { return a + b; } type ParamsType = Parameters; / 结果如下: type ParamsType = [a: number, b: number] // sum 函数参数组成的元组 /

  1. <a name="dL25X"></a>
  2. ## InstanceType 和 ConstructorParameters
  3. 获取构造函数类型的实例类型
  4. ```typescript
  5. class Person {
  6. constructor(public name: string, public age: number) {}
  7. }
  8. type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
  9. // 获取类的构造函数的参数类型
  10. type constructorParameters = ConstructorParameters<typeof Person>;
  11. /*
  12. constructorParameters 的结果如下:
  13. type constructorParameters = [name: string, age: number]
  14. */
  15. type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
  16. type Instance = InstanceType<typeof Person>;
  17. /*
  18. Instance 结果如下:
  19. type Instance = Person
  20. */
  21. let instance: Instance = { name: '', age: 1 };

infer 的应用案例

infer 最早出现在此 PR 中,表示在 extends 条件语句中待推断的类型变量。

下面看个简单的例子,注意:代码中的 infer P 表示待推断的函数参数。

  1. // 如果 T 能赋值给 (...args: infer P) => any 则返回推断出的类型变量 P,否则返回 T。
  2. type ParamType<T> = T extends (...args: infer P) => any ? P : T;
  3. interface User {
  4. name: string,
  5. age: number
  6. }
  7. type Func = (user: User) => void;
  8. type Param = ParamType<Func>; // Param = [user: User]
  9. type AA = ParamType<string>; //AA = string

上面的例子中我们在函数类型的参数中使用了 infer ,并不是说 infer 只能用于函数中。

  1. type Person<T> = T extends { name: infer A } ? A : never;
  2. type P = Person<{name: string}>; // P = string

从上面的例子可以看出 infer 也可以用于其他地方。

tuple 转 union

  1. type ElementOf<T> = T extends Array<infer E> ? E : never;
  2. type Ttuple = [string, number, boolean];
  3. type TupleToUnion = ElementOf<Ttuple>; // TupleToUnion = string | number | boolean

交叉类型

  1. type T1 = { name: string };
  2. type T2 = { age: number };
  3. type Intersection<T> = T extends { a: (x: infer U) => void, b: (x: infer U) => void } ? U : never;
  4. type T3 = Intersection<{ a: (x:T1) => void, b:(x:T2) => void }>; // T3 = T1 & T2
  5. const person: T3 = { name: '', age: 18 };

内置工具类型

TS 中内置了一些工具类型来帮助我们更好地使用类型系统
utility-types)
TypeScript中增加了对映射类型修饰符的控制
具体而言,一个 readonly 或 ? 修饰符在一个映射类型里可以用前缀 + 或-来表示这个修饰符应该被添加或移除

符号 含义
+? 变为可选
-? 变为必选

Partial

Partial 可以将传入的属性由非可选变为可选,具体使用如下

  1. interface Person {
  2. name: string,
  3. age: number
  4. }
  5. type PersonPartial = Partial<Person>;
  6. const p: PersonPartial = {};

Partial 的代码如下:

  1. type Partial<T> = {
  2. [P in keyof T]?: T[P];
  3. };

类型递归

  1. interface Scores {
  2. math: number,
  3. english: number
  4. }
  5. interface Student {
  6. name: string,
  7. age: number,
  8. scores: Scores
  9. }
  10. type StudentPartial = Partial<Student>;
  11. /*
  12. StudentPartial = {
  13. name?: string | undefined;
  14. age?: number | undefined;
  15. scores?: Scores | undefined;
  16. }
  17. */
  18. const s: StudentPartial = {name:'', age:1};

scores 必传

  1. const s: StudentPartial = { name: '', age: 1, scores: {math: 1, english: 2}};

怎么不传呢,我们可以自定义 DeepPartial

  1. type DeepPartial<T> = {
  2. [U in keyof T]?: T[U] extends object
  3. ? DeepPartial<T[U]>
  4. : T[U]
  5. };

修改后的代码如下:

  1. interface Scores {
  2. math: number,
  3. english: number
  4. }
  5. interface Student {
  6. name: string,
  7. age: number,
  8. scores: Scores
  9. }
  10. type DeepPartial<T> = {
  11. [U in keyof T]?: T[U] extends object
  12. ? DeepPartial<T[U]>
  13. : T[U]
  14. };
  15. type StudentPartial = DeepPartial<Student>;
  16. /*
  17. StudentPartial = {
  18. name?: string | undefined;
  19. age?: number | undefined;
  20. scores?: DeepPartial<Scores> | undefined;
  21. }
  22. */
  23. const s: StudentPartial = { name: '', age: 1, scores: {}};

这样 scores 不传值也不会报错了。

Required

Required 可以将传入的属性中的可选项变为必选项,这里用了 -? 修饰符来实现。

  1. interface Person {
  2. name?: string,
  3. age?: number
  4. }
  5. type Required<T> = {
  6. [P in keyof T]-?: T[P];
  7. };
  8. type RequiredPerson = Required<Person>;
  9. /*
  10. RequiredPerson = {
  11. name: string;
  12. age: number;
  13. }
  14. */
  15. const p: RequiredPerson = { name: '', age: 18 };

Readonly

Readonly 通过为传入的属性每一项都加上 readonly 修饰符来实现

  1. interface Person {
  2. name: string,
  3. age: number
  4. }
  5. type ReadonlyPerson = Readonly<Person>
  6. const p: ReadonlyPerson = {
  7. name: '',
  8. age: 18
  9. };
  10. // Cannot assign to 'name' because it is a read-only property.
  11. // p.name = 'f';
  12. // Cannot assign to 'age' because it is a read-only property.
  13. // p.age = 19;

如果我们只想某个属性不可选,可以像下面这样写:

  1. interface Person {
  2. readonly name: string,
  3. age: number
  4. }
  5. const p: Person = {
  6. name: '',
  7. age: 18
  8. };
  9. // Cannot assign to 'name' because it is a read-only property.
  10. // p.name = 'f';
  11. p.age = 19;

如果我们不能改 Person 接口的话,可以像下面这样写:

  1. interface Person {
  2. name: string,
  3. age: number
  4. }
  5. type ReadonlyPerson = Person & { readonly name: string };
  6. const p: ReadonlyPerson = {
  7. name: '',
  8. age: 18
  9. };
  10. // Cannot assign to 'name' because it is a read-only property.
  11. // p.name = 'f';
  12. p.age = 19;

Pick

Pick 能够帮助我们从传入的属性中摘取某一项返回,在一个声明好的对象中,挑选一部分出来组成一个新的声明对象

  1. interface Person {
  2. name: string,
  3. age: number
  4. }
  5. type PickPerson = Pick<Person, 'name'>; // PickPerson = { name: string; }

Pick 的源代码如下:

  1. type Pick<T, K extends keyof T> = {
  2. [P in K]: T[P];
  3. };

Pick 和 Extract 的区别

它们两个的功能不同 Pick 是在一个声明好的对象中,挑选一部分出来组成一个新的声明对象,Extract 是从 T 中抽出可分配给 U 的属性构成新的类型。

Pick 的源码:

  1. type Pick<T, K extends keyof T> = {
  2. [P in K]: T[P];
  3. };

Extract 的源码:

  1. type Extract<T, U> = T extends U ? T : never;

Record

构造一个类型,该类型具有一组属性 K ,每个属性的类型为 T 。可用于将一个类型的属性映射为另一个类型。Record 后面的泛型就是对象键和值的类型。他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型

简单理解:K 对应对应的key,T 对应对象的 value,返回的就是一个声明好的对象

Record 源码如下:

  1. type Record<K extends keyof any, T> = {
  2. [P in K]: T;
  3. };

keyof any 的值为 string | number | symbol

  1. type Key = keyof any; // Key = string | number | symbol

注意: keyof 后面跟的是类型,不是变量。

Recodr 的源码可以看成下面这样:

  1. type Record<K extends string | number | symbol, T> = {
  2. [P in K]: T;
  3. };

也就是 P 的类型可以是 string | number | symbol

上面我们对 Record 进行了简单介绍,下面我们来举个例子看看怎么用它:

  1. type PersonType = 'name' | 'age' | 'gender';
  2. type Person = Record<PersonType, string>;
  3. /*
  4. Person = {
  5. name: string;
  6. age: string;
  7. gender: string;
  8. }
  9. */

案例2:

  1. function mapObject<K extends string | number, T, U>(obj: Record<K, T>, map: (x: T) => U): Record<K, U> {
  2. let result: any = {};
  3. for (const key in obj) {
  4. result[key] = map(obj[key]);
  5. }
  6. return result;
  7. }
  8. let names = { 0: 'hello', 1: 'world' };
  9. let lengths = mapObject<string | number, string, number>(names, (s: string) => s.length);
  10. console.log(lengths);//{ '0': 5, '1': 5 }

自定义高级类型

Proxy

  1. interface Props {
  2. name: string;
  3. age: number;
  4. }
  5. const obj: Props = {
  6. name: 'f',
  7. age: 18
  8. };
  9. type Proxy<T> = {
  10. set(value: T): void;
  11. get(): T;
  12. };
  13. type Proxify<T> = { [P in keyof T]: Proxy<T[P]> };
  14. function proxify<T>(obj: T): Proxify<T> {
  15. const res = <Proxify<T>>{};
  16. for (let k in obj) {
  17. type KeyType = typeof k;
  18. res[k] = {
  19. set(value: T[KeyType]) {
  20. obj[k] = value;
  21. },
  22. get() {
  23. return obj[k];
  24. }
  25. };
  26. }
  27. return res;
  28. }
  29. const proxyProps = proxify<Props>(obj);
  30. console.log(proxyProps);
  31. function unProxify<T>(obj: Proxify<T>): T {
  32. const res = <T>{};
  33. for (const k in obj) {
  34. res[k] = obj[k].get();
  35. }
  36. return res;
  37. }
  38. const originProps = unProxify(proxyProps);
  39. console.log(originProps); // {name: 'f', age: 18}

SetDifference

  1. type SetDifference<A, B> = A extends B ? never : A;
  2. type A = string | number;
  3. type B = number | boolean;
  4. type AB = SetDifference<A, B>; // type AB = string

从上面的例子可以看出它和 Exclude 的效果是一样的,下面我们来看下两个的实现源码:

  1. type Exclude<T, U> = T extends U ? never : T;
  2. type SetDifference<A, B> = A extends B ? never : A;

Omit

以一个类型为基础支持剔除某些属性,然后返回一个新类型。

  1. type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
  2. type Person = {
  3. name: string;
  4. age: string;
  5. gender: number;
  6. };
  7. type PersonType = Omit<Person, 'gender'>;
  8. /*
  9. PersonType = {
  10. name: string;
  11. age: string;
  12. }
  13. */

下面我们来说下它的源码:

  1. type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

keyof 的作用是获取某个类型的所有键,它会返回一个联合类型:

  1. type A = keyof { name: '', age: 10 } // A = "name" | "age"
  2. type B = keyof any // B = string | number | symbol

Exclude 的作用前面我们已经讲过了,简单来说就是将类型 T 和 类型 U 进行对比,返回 T 中独有的。

  1. type A = Exclude<string|number|boolean, string|number>; // A = boolean
  2. // 源码
  3. type Exclude<T, U> = T extends U ? never : T;

Pick 能够帮助我们从传入的属性中摘取某一项返回,在一个声明好的对象中,挑选一部分出来组成一个新的声明对象。

  1. type A = Pick<{ name: 'f', age: 18 }, 'name'>;
  2. /*
  3. A = {
  4. name: 'f';
  5. }
  6. */
  7. // 源码
  8. type Pick<T, K extends keyof T> = {
  9. [P in K]: T[P];
  10. };

通过上面的学习我们理清楚了一些关于 Omit 的知识点,下面我们来推导下开头的例子,以达到更深入的理解:

  1. type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
  2. type Person = {
  3. name: string;
  4. age: string;
  5. gender: number;
  6. };
  7. type PersonType = Omit<Person, 'gender'>; =>
  8. type PersonType = Pick<Person, Exclude<'name'|'age'|'gender', 'gender'>> =>
  9. type PersonType = Pick<Person, 'name'|'age'> =>
  10. type PersonType = Pick<Person, 'name'|'age'> =>
  11. type PersonType = {
  12. [P in 'name'|'age']: Person[P] =>
  13. }
  14. type PersonType = {
  15. name: sting,
  16. age: number
  17. }

Diff

Diff<T, U>找出 T 和 U 不同的地方:

  1. type SetDifference<A, B> = A extends B ? never : A;
  2. type Diff<T extends object, U extends object> = Pick<T, SetDifference<keyof T, keyof U>>;
  3. type A = Diff<{ name: string, age: number }, { name: string }> // A = {age: number;}

推导下:

  1. type SetDifference<A, B> = A extends B ? never : A;
  2. type A = Diff<{ name: string, age: number }, { name: string }> =>
  3. type A = Pick<{ name: string, age: number }, SetDifference<'name'|'age', 'name'>> =>
  4. type A = Pick<{ name: string, age: number }, 'name'|'age' extends 'name' ? never : A> =>
  5. type A = Pick<{ name: string, age: number }, 'age'> =>
  6. type A = {age: number}

Intersection

Intersection<T, U> 找出 T 和 U 相同的部分。

  1. type Intersection<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
  2. type A = { name: string, age: number, gender: number };
  3. type B = { gender: string };
  4. type AB = Intersection<A, B>; // AB = { gender: number; }
  5. type BA = Intersection<B, A>; // BA = { gender: string; }

我们先来复习下 Extract<T, U> ,它的作用主要是从类型 T 中取可兼容类型 U 的类型

  1. type A = Extract<string | number | boolean, boolean>; // A = boolean
  2. // 源码
  3. type Extract<T, U> = T extends U ? T : never;

推导下

  1. type Intersection<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
  2. type Extract<T, U> = T extends U ? T : never;
  3. type A = { name: string, age: number, gender: number };
  4. type B = { gender: string };
  5. type AB = Intersection<A, B>; =>
  6. type AB = Pick<{ name: string, age: number, gender: number }, 'name'|'age'|'gender' extends 'gender' ? T : never & 'gender' extends 'name'|'age'|'gender' ? U : never>; =>
  7. type AB = Pick<{ name: string, age: number, gender: number }, 'gender' & 'gender'>; =>
  8. type AB = Pick<{ name: string, age: number, gender: number }, 'gender'>; =>
  9. type AB = { gender: number };

简单总结下就是 Intersection<T, U> 求的交集保留 T 里面的。注意,这和 & 是不一样的:

  1. type A = { name: string, age: number, gender: number };
  2. type B = { gender: string };
  3. type AB = A & B;
  4. let a!: never;
  5. const ab: AB = { name: '', age: 1, gender: a };

A 里面的 genderB里面的 gender 相交后得到的 gender 的值为 never

Overwrite

顾名思义,是用U的属性覆盖T的相同属性。

  1. type SetDifference<A, B> = A extends B ? never : A;
  2. type Diff<T extends object, U extends object> = Pick<T, SetDifference<keyof T, keyof U>>;
  3. type Intersection<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
  4. type Overwrite<T extends object, U extends object, I = Diff<T, U> & Intersection<U, T>> = Pick<I, keyof I>;
  5. type Old = { name: string; age: number; gender: number };
  6. type New = { age: string; other: string };
  7. // 从结果我们可以看出,只是覆盖了同名属性,并没有添加新属性。
  8. type Res = Overwrite<Old, New>; // { name: string; age: string; gender: number; }

下面我们来推导下上面的结果:

  1. type Res = Overwrite<Old, New>;
  2. =>
  3. type Res = Overwrite<Old, New, I = Diff<Old, NEW> & Intersection<NEW, Old>> = Pick<I, keyof I>;
  4. =>
  5. type Res = Overwrite<Old, New, I = Pick<Old, SetDifference<keyof Old, keyof New>> & Pick<New, Extract<keyof New, keyof Old> & Extract<keyof Old, keyof New>>> = Pick<I, keyof I>;
  6. =>
  7. type Res = Overwrite<Old, New, I = Pick<Old, SetDifference<'name'|'age'|'gender', 'age'|'other'>> & Pick<New, Extract<'age'|'other', 'name'|'age'|'gender'> & Extract<keyof 'name'|'age'|'gender', 'age'|'other'>>> = Pick<I, keyof I>;
  8. =>
  9. type Res = Overwrite<Old, New, I = Pick<Old, 'name'|'gender'> & Pick<New, 'age>> = Pick<I, keyof I>;
  10. =>
  11. type Res = Overwrite<Old, New, I = {
  12. name: string;
  13. gender: number;
  14. } & {
  15. age: string;
  16. } = Pick<I, keyof I>;
  17. =>
  18. type Res = Overwrite<Old, New, I = {
  19. name: string;
  20. gender: number;
  21. } & {
  22. age: string;
  23. } = Pick<{name: string, age: string, gender: number}, 'name'|'gender'|'age'>;
  24. =>
  25. type Res = { name: string; age: string; gender: number; }

如果说我们既想实现覆盖,又想实现添加,该怎么办呢?

  1. type SetDifference<A, B> = A extends B ? never : A;
  2. type Diff<T extends object, U extends object> = Pick<T, SetDifference<keyof T, keyof U>>;
  3. type Intersection<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
  4. + type Overwrite<T extends object, U extends object, I = Diff<T, U> & U> = Pick<I, keyof I>;
  5. type Old = { name: string; age: number; gender: number };
  6. type New = { age: string; other: string };
  7. type Res = Overwrite<Old, New>; // {name: string; age: string; gender: number;other: string;}

Merge

Merge的作用是将两个对象的属性合并

  1. type A = {
  2. name: string,
  3. age: number
  4. };
  5. type B = {
  6. name: string,
  7. gender: number
  8. };
  9. type Compute<T extends any> = T extends Function ? T : { [P in keyof T]: T[P] };
  10. type R = Compute<{ a: '', b: '' }>; //R = { a: ''; b: ''; }
  11. type Merge<A extends object, B extends object> = Compute<A & Omit<B, keyof A>>;
  12. type R1 = Merge<A, B>;
  13. /*
  14. R1 = {
  15. name: string;
  16. age: number;
  17. gender: number;
  18. }
  19. */

Mutable

将 T 的所有属性的 readonly 移除

  1. interface Person{
  2. readonly name: string,
  3. readonly age: number
  4. }
  5. type Mutable<T> = {
  6. -readonly [P in keyof T]: T[P]
  7. };
  8. const person: Mutable<Person> = {
  9. name: '',
  10. age: 18
  11. };
  12. person.name = 'f';
  13. person.age = 1;

面试题综合实战