首页>国内 > 正文

15 种TypeScript最常用的实用程序类型

2022-10-24 15:49:21来源:web前端开发

为了方便 TypeScript 用户,TypeScript 开发团队为我们提供了许多有用的内置实用程序类型。通过这些实用类型,我们

可以轻松地转换类型、提取类型、排除类型,或者获取函数的参数类型或返回值类型。


(资料图片仅供参考)

在本文中,我从 TypeScript 的内置实用程序类型中挑选了 15 种非常有用的类型,并以图像的形式介绍了它们的用法和内部工作原理,看完这篇文章,相信你可以真正掌握这些内置实用程序类型的用法。

1.Partial

构造一个类型,其中 Type 的所有属性都设置为可选。

/** * Make all properties in T optional.  * typescript/lib/lib.es5.d.ts */type Partial = {    [P in keyof T]?: T[P];};
2. Required

构造一个类型,该类型由设置为 required Type 的所有属性组成,部分的反义词。

/** * Make all properties in T required. * typescript/lib/lib.es5.d.ts */type Required = {    [P in keyof T]-?: T[P];};
3.Readonly

构造一个 Type 的所有属性都设置为 readonly 的类型,这意味着构造类型的属性不能被重新分配。

/** * Make all properties in T readonly. * typescript/lib/lib.es5.d.ts */type Readonly = {    readonly [P in keyof T]: T[P];};
4.Record

构造一个对象类型,其属性键为 Keys,其属性值为 Type,此实用程序可用于将一种类型的属性映射到另一种类型。

/** * Construct a type with a set of properties K of type T. * typescript/lib/lib.es5.d.ts */type Record = {    [P in K]: T;};
5. Exclude

通过从 UnionType 中排除可分配给 ExcludedMembers 的所有联合成员来构造类型。

/** * Exclude from T those types that are assignable to U. * typescript/lib/lib.es5.d.ts */type Exclude = T extends U ? never : T;
6. Extract

通过从 Type 中提取所有可分配给 Union 的联合成员来构造一个类型。

/** * Extract from T those types that are assignable to U. * typescript/lib/lib.es5.d.ts */type Extract = T extends U ? T : never;
7. Pick

通过从 Type 中选择一组属性 Keys(字符串文字或字符串文字的联合)来构造一个类型。

/** * From T, pick a set of properties whose keys are in the union K. * typescript/lib/lib.es5.d.ts */type Pick = {    [P in K]: T[P];};
8.Omit

通过从 Type 中选择所有属性然后删除 Keys(字符串文字或字符串文字的联合)来构造一个类型。

/** * Construct a type with the properties of T except for those  * in type K.  * typescript/lib/lib.es5.d.ts */type Omit = Pick>;
9. NonNullable

通过从 Type 中排除 null 和 undefined 来构造一个类型。

/** * Exclude null and undefined from T. * typescript/lib/lib.es5.d.ts */type NonNullable = T extends null | undefined ? never : T;
10. Parameters

从函数类型 Type 的参数中使用的类型构造元组类型。

/** * Obtain the parameters of a function type in a tuple. * typescript/lib/lib.es5.d.ts */type Parameters any> = T extends   (...args: infer P) => any ? P : never;
11. ReturnType

构造一个由函数 Type 的返回类型组成的类型。

/** * Obtain the return type of a function type. * typescript/lib/lib.es5.d.ts */type ReturnType any> = T extends (...args: any) => infer R ? R : any;
12. Uppercase

将字符串文字类型转换为大写。

13.小写

将字符串文字类型转换为小写。

14. 大写

将字符串文字类型的第一个字符转换为大写。

15. 取消大写

将字符串文字类型的第一个字符转换为小写。

除了上述这些实用程序类型之外,还有一些其他常用的 TypeScript 内置实用程序类型,具体如下:

ConstructorParameters:根据构造函数类型的类型构造元组或数组类型。它产生一个包含所有参数类型的元组类型(如果 Type 不是函数,则类型 never )。InstanceType:构造一个由Type中构造函数的实例类型组成的类型。ThisParameterType:为函数类型提取此参数的类型,如果函数类型没有此参数,则为未知。

本文介绍的实用程序类型在内部使用了有关映射类型、条件类型和推断类型推断的知识。如果你对映射类型和条件类型不熟悉,后面我将继续分享一些这个方面的知识。

关键词: 实用程序 文字类型 所有属性 构造类型

相关新闻

Copyright 2015-2020   IT网  版权所有 联系邮箱:897 18 09@qq.com  备案号:豫ICP备2021032478号-48