一看就懂的TypeScript工具类型

开发 前端
Partial,将T类型中的所有属性变为可选属性; Required,将T类型中的所有属性变为必选属性; Readonly,将T类型中的所有属性变为只读属性。

TypeScript是一种静态类型检查的编程语言,它内置了许多基本数据类型,如字符串、数字和布尔型等。除了基本数据类型,当某种类型对于大多数代码来说都非常有用时,它们就会被添加到TypeScript中并且被大家使用而无需担心它们的可用性。这些内置在TS中的类型我们称之为工具类型,这些工具类型位于TS安装目录typescript/lib/lib.es5.d.ts,熟悉这些工具类型,可以帮助我们提高开发效率。

Partial<T>、Required<T> 与 Readonly<T>

该组工具类型为改操作的工具类型,具体为将类型T的所有属性都改为可选、必选或只读。

定义:

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};
/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

知识点:

in:关键字,用来实现遍历;

keyof:关键字,索引类型查询,用来获取类型的所有键,返回的类型是联合类型;

?:修饰符,表示可选属性;

readonly:修饰符,表示只读属性;

-:修饰符,添加在“?”或"readonly"修饰符之前,表示移除“?”或"readonly"修饰符。

作用:

Partial,将T类型中的所有属性变为可选属性; Required,将T类型中的所有属性变为必选属性; Readonly,将T类型中的所有属性变为只读属性。

应用:

interface Text {
  size: number
  color: string
}
type T = Partial<Text>
type R = Required<Text>
type O = Readonly<Text>

新定义的T类型中的属性均为Text类型属性,且均为可选;新定义的R类型中的属性均为Text类型属性,且均为必选;新定义的O类型中的属性均为Text类型属性,且均为只读。

Record<K,T>

该类型可视作增操作相关的工具类型,根据我们指定的键值类型,新增一个对象类型。

定义:

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

知识点:

keyof any:上面介绍过keyof(关键字,用来获取类型的所有键,返回的类型是联合类型),当对any使用keyof索引类型查询时,结果类型为固定的联合类型“string | number | symbol”;

K extends keyof any:泛型约束,定义了类型K的最大范围为联合类型“string | number | symbol”。

作用:

根据给定的属性名类型和属性类型创建一个新的对象类型。

应用:

type K = 'size'|'color'
type T = number
type R = Record<K, T>

新定义的R类型,包括属性size和color,且类型均为number。

Exclude<T,U> 与 Extract<T,U>

该组类型可以视作查操作相关的工具类型,查出T类型中与U类型无关的属性或相关的属性。

定义:

/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

/**
 * Extract from T those types that are assignable to U
 */
type Extract<T, U> = T extends U ? T : never;

知识点:

T extends U ? X : Y:条件类型,extends是关键字,若类型T能够赋值给类型U,则条件类型的结果为类型X,否则为类型Y。

作用:

根据条件类型的定义,Exclude类型中若T类型中的属性存在于U类型,则返回never,也就是从类型T中剔除所有类型U的属性。Extract则恰恰和Exclude相反,返回类型T和类型U的交集。

应用:

interface Text {
  size: number
  color: string
}
interface Img {
  width: number
  color: string
}
type T = Exclude<Text,Img>
type R = Extract<Text,Img>

新定义的T类型,只有size属性;新定义的R类型,只包含color属性。

Pick<T,K>、Omit<T,K>与NonNullable

该组工具类型为删操作相关的工具类型,包括剔除与指定键相关、无关或null、undefined类型操作的工具类型。

定义:

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
/**
 * Exclude null and undefined from T
 */
type NonNullable<T> = T extends null | undefined ? never : T;

作用:

Pick类型从已有对象类型T中选取选定的属性及其类型K创建新的类型。Omit与Pick类型相反,从已有对象类型T中剔除选定的属性及其类型K创建新的类型。NonNullable与Omit相似,返回的结果为从T类型中剔除null and undefined类型。

应用:

interface Text {
  size: number
  color: string
}
type T = Pick<Text,'size'>
type R = Omit<Text,'size'>
type N = NonNullable<Text|null|undefinde>

新定义的T类型,只包括Text类型中的属性size及其类型;新定义的T类型,只包括Text类型中的属性color及其类型;新定义的N类型,只包括Text类型。

Parameters、ConstructorParameters、ReturnType与InstanceType

该组工具类型为与函数相关的工具类型,包括获取普通函数参数和返回值的工具类型和获取构造函数参数和返回值的构造类型。

定义:

/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

/**
 * Obtain the parameters of a constructor function type in a tuple
 */
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;

/**
 * Obtain the return type of a function type
 */
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

/**
 * Obtain the return type of a constructor function type
 */
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;

知识点:

infer:关键字,在extends条件类型语句(T extends U ?X : Y)中,允许在类型U的位置上使用关键字infer定义可推断的类型变量,可推断的类型变量只允许在类型X的位置上使用。简单应用如下,取出数组中的类型:

type ExtractArrayItemType<T> = T extends (infer U)[] ? U : T;
// 条件判断为 true,返回 U
type T = ExtractArrayItemType<string[]>; // string

作用:

Parameters工具类型能够获取函数类型的参数类型,并使用参数类型构造一个元组类型; ConstructorParameters工具类型可以把构造函数的参数类型作为一个元组类型返回;ReturnType工具类型可以获取函数的返回值类型; InstanceType工具类型可以获取构造函数的返回类型;

应用:

type Fn = (a: string, b: number) => string;
type FnParamTypes = Parameters(Fn);  // [string, number]
type FnReturnType = ReturnType(Fn); // string

interface FunctionConstructor {
  new(...args: string[]): Function;
  (...args: string[]): Function;
  readonly prototype: Function;
}

type ConstructorParamTypes = ConstructorParameters(FunctionConstructor) // string[]

type ConstructorInstanceType = InstanceType(FunctionConstructor) // Function

ThisParameterType、OmitThisParameter与ThisType

该组类型均为与this相关的工具类型。

定义:

/**
 * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
 */
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;

/**
 * Removes the 'this' parameter from a function type.
 */
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
/**
 * Marker for contextual 'this' type
 */
interface ThisType<T> { }

知识点:

unknown:顶端类型,TypeScript中仅有any和unknown两种顶端类型,所有其他类型都可以赋值给两者,但unknown只能赋值给any类型和unknown类型。TypeScript中只有一个尾端类型never,是其他所有类型的子类型。

作用 ThisParameterType类型可以获取函数参数中this参数的类型;OmitThisParameter类型可以剔除函数参数中this参数的类型;ThisType类型可以对象字面量中this的类型。

应用

interface Foo {
    x: number
};

function fn(this: Foo) {}

type Test = ThisParameterType<typeof fn>; // Foo

type Fn = (this: Foo) => void

type NonReturnFn = OmitThisParameter<Fn>; // () => void

let obj: ThisType<{x: number, getX: () => number}>

obj = {
  x: 100,
  getX(){
    return this.x
  }
}

以上简单介绍了TypeScript中的自带工具类型,TypeScript与JavaScript有相通之处,但又有更多的不同和背景知识,只有内化了这些知识同时不断地练习才能有效掌握这一门语言。


图片

责任编辑:武晓燕 来源: 大转转FE
相关推荐

2020-09-21 08:33:12

线程池调度Thread Pool

2020-04-15 08:33:43

Netty网络通信

2018-09-28 14:28:28

MySQL存储过程

2021-07-15 09:55:47

systemdLinux文件

2020-03-27 09:06:54

选择排序算法冒泡排序

2022-08-15 19:49:57

Consul架构注册中心

2021-05-14 07:11:49

方法调用类加载

2021-12-30 09:10:28

游戏开发开发技术热点

2022-05-29 22:55:00

适配器设计模式

2019-08-14 10:20:32

算法数组链表

2019-01-15 09:55:24

RAID磁盘阵列数据存储

2020-05-09 14:40:29

UI设计开发

2015-07-21 13:07:14

Reactjs教程

2022-06-19 22:54:08

TypeScript泛型工具

2022-03-21 21:05:40

TypeScript语言API

2021-01-07 10:30:23

设计模式

2021-05-13 07:30:27

Kafka消息流系统

2019-08-22 09:22:44

数据结构二叉搜索树

2021-06-01 06:01:35

SSO单点登录

2022-06-20 08:56:25

Kafka微服务运维
点赞
收藏

51CTO技术栈公众号