一看就懂的TypeScript工具类型

a92b9f15533e2c63c18dee946253d774.png

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有相通之处,但又有更多的不同和背景知识,只有内化了这些知识同时不断地练习才能有效掌握这一门语言。

想了解更多转转公司的业务实践,点击关注下方的公众号吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值