TS高级类型:Extract 与 Exclude

2022-03-19  本文已影响0人  wyc0859

Extract 是TS提供的一个TS高级type类型【简称TS高级类型】

Extract 用于类

class People {
  public name!: string;
  public age!: number;
  public address!: string;
  eat() {}
}

class CnPeople extends People {
  private phone!: string;
}

let cp = new CnPeople();

// 现在这个Extractxx是自定义的,不是内置。但功效和内置的Extract一样
type Extractxx<T, U> = T extends U ? T : never;

// 定律1:子类 extends 父类; 永远true,返回T类型
type extractType = Extractxx<CnPeople, People>; // CnPeople

// 定律: 父类 extends 子类; 只有实例属性或实例方法一样时则为true
type extractType2 = Extractxx<People, CnPeople>; // never 

Extract 用于函数

type func1 = (one: number, two: string) => string;
type func2 = (one: number) => string;

//  参数少的函数类型 extends 参数多的函数类型 返回true
//  参数多的函数类型 extends 参数少的函数类型 返回false
type beginType1 = func1 extends func2 ? func1 : never; //never
type beginType2 = func2 extends func1 ? func2 : never; //func2

//这个Extract是TS内置方法
type tType1 = Extract<func1, func2>; //never
type tType2 = Extract<func2, func1>; //= (one: number) => string  和上面有区别

Extract 用于基础类型

type base1 = Extract<string | number, string>; //string || never; //实测是string
type base2 = Extract<string, string | number>; //string

Exclude 刚好和 Extract 相反

type ec1 = Exclude<func1, func2>; //(one: number, two: string) => string;
type ec2 = Exclude<string, string | number>; //never
上一篇 下一篇

猜你喜欢

热点阅读