美文网首页
TS高级类型:Extract 与 Exclude

TS高级类型:Extract 与 Exclude

作者: wyc0859 | 来源:发表于2022-03-19 16:33 被阅读0次

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

相关文章

  • TS高级类型:Extract 与 Exclude

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

  • ts高级类型

    类型的且运算 上面的代码c变量的类型为A和B,也就是要同时满足A和B里所有的字段定义,name、age和garde...

  • TS: 高级类型

    TS 文档是有一章叫高级类型,其实并不是真的“高级”,他实际的意思是将普通的类型用“某种方式”组合起来形成一个“组...

  • TypeScript自带的工具泛型

    前言 前面总结了ts的高级类型,下面再来说说ts给我们提供的一些基于这些高级类型而成的工具泛型。 Partial ...

  • 常用TS高级类型

    类类型 写法: 应用: 函数返回类型 写法: 参数类型 写法: 应用: 类型推导infer 参考 https://...

  • typescript修炼指南(三)

    大纲 本章主要讲解一些ts的高级用法,涉及以下内容: 类型断言与类型守卫 in关键词和is关键词 类型结构 装饰器...

  • ts type类型 高级类型 类型保护

    type type 关键字用来定义一种类型举个例子 交叉类型 表示将多个类型合并为一个类型,多用在混入 联合类型 ...

  • TS的数据类型与高级类型相关

    TS中常见的数据类型 JS里面有七种数据类型。Number,String,Boolean, Null, Undef...

  • TS入门2019-08-13

    ts和js出了类型声明其他的都是一样的。(ts就是比js多了一个类型声明) ts 与 js 相比,其实就是把类型给...

  • Ts高级类型(Utility Types)

    学习TypeScript的过程中发现对某些UtilityTypes不是很理解,就重新在文档上系统学习了一遍,Typ...

网友评论

      本文标题:TS高级类型:Extract 与 Exclude

      本文链接:https://www.haomeiwen.com/subject/psnbdrtx.html