【TS】1713- 一看就懂的TypeScript工具类型

前端自习课

共 6405字,需浏览 13分钟

 ·

2023-06-14 14:13

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

Partial、Required 与 Readonly

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

定义

      /**
 * Make all properties in T optional
 */
type Partial = {
    [P in keyof T]?: T[P];
};
/**
 * Make all properties in T required
 */
type Required = {
    [P in keyof T]-?: T[P];
};
/**
 * Make all properties in T readonly
 */
type Readonly = {
    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
type R = Required
type O = Readonly

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

Record

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

定义

      /**
 * Construct a type with a set of properties K of type T
 */
type Record = {
    [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

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

Exclude 与 Extract

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

定义

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

/**
 * Extract from T those types that are assignable to U
 */
type Extract = 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
type R = Extract

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

Pick、Omit与NonNullable

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

定义

      /**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick = {
    [P in K]: T[P];
};
/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit = Pick>;
/**
 * Exclude null and undefined from T
 */
type NonNullable = 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'size'>
type R = Omit'size'>
type N = NonNullable

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

Parameters、ConstructorParameters、ReturnType与InstanceType

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

定义

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

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

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

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

知识点

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

      type ExtractArrayItemType = T extends (infer U)[] ? U : T;
// 条件判断为 true,返回 U
type T = ExtractArrayItemType; // 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 extends (this: infer U, ...args: any[]) => any ? U : unknown;

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

知识点

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; // Foo

type Fn = (this: Foo) => void

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

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

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

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




往期回顾
#

如何使用 TypeScript 开发 React 函数式组件?

#

11 个需要避免的 React 错误用法

#

6 个 Vue3 开发必备的 VSCode 插件

#

3 款非常实用的 Node.js 版本管理工具

#

6 个你必须明白 Vue3 的 ref 和 reactive 问题

#

6 个意想不到的 JavaScript 问题

#

试着换个角度理解低代码平台设计的本质

回复“加群”,一起学习进步

浏览 22
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报