本文转载自微信公众号「xyz编程日记」,作者小综哥 。转载本文请联系xyz编程日记公众号。

为平谷等地区用户提供了全套网页设计制作服务,及平谷网站建设行业解决方案。主营业务为成都网站建设、网站建设、平谷网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
TS在全局内置了很多Utility Types,可以极大的提高我们开发效率。所以本文就是详细介绍、理解、掌握。
作用:它会将Type内所有属性置为可选,返回一个给定类型Type的子集。
示例:
- interface Todo {
 - title: string;
 - description: string;
 - }
 - // 场景:只想更新toTo部分属性,Partial的使用就比较优雅了
 - function updateTodo(todo: Todo, fieldsToUpdate: Partial
 ) { - return { ...todo, ...fieldsToUpdate };
 - }
 - const todo1 = {
 - title: "organize desk",
 - description: "clear clutter",
 - };
 - const todo2 = updateTodo(todo1, {
 - description: "throw out trash",
 - });
 
我们看看Partial背后是如何实现的:
- /**
 - * Make all properties in T optional
 - */
 - type Partial
 = { - [P in keyof T]?: T[P];
 - };
 
上面定义涉及的知识点:
作用:Required与上面的Partial相反,构建返回一个Type的所有属性为必选的新类型。
示例:
- interface Props {
 - a?: number;
 - b?: string;
 - }
 - const obj: Props = { a: 5 };
 - const obj2: Required
 = { a: 5 }; // Property 'b' is missing in type '{ a: number; }' but required in type 'Required '. 
我们看看Required背后的实现:
- /**
 - * Make all properties in T required
 - */
 - type Required
 = { - [P in keyof T]-?: T[P];
 - };
 
上面定义涉及的知识点:
在TS2.8版本改善了对映射类型修饰符的支持。
在TS2.8版本之前,支持对映射类型的属性添加readonly、?的修饰符,但是并没有提供移除修饰符的能力。默认它的修饰符是跟映射类型保持一致的,有兴趣的可以看这个PR以及它fix的issue。那现在映射类型它支持通过+或者-来添加or移除readonly或者?修饰符。
我们看一个示例:
- type A = { readonly a? : number, b: string };
 - type MockRequired
 = { - -readonly [P in keyof T]-?: T[P] // 这里可以不需要-?
 - };
 - const test: MockRequired = { // 我希望a是必须的
 - a: 10,
 - b: 'b'
 - };
 - test.a = 20; // 我希望可以修改a
 
到这里我们就理解-?的含义了。
作用:将Type所有属性置为只读。示例:
- interface Todo {
 - title: string;
 - }
 - const todo: Readonly
 = { - title: "Delete inactive users",
 - };
 - todo.title = "Hello"; // Cannot assign to 'title' because it is a read-only property.
 
我们看看Readonly背后的实现:
- /**
 - * Make all properties in T readonly
 - */
 - type Readonly
 = { - readonly [P in keyof T]: T[P];
 - };
 
这里有上面的知识铺垫就比较好理解了,只需要知道映射类型支持修饰符readonly、?。
另外这里补充下readonly的含义跟JS的const不能修改的含义一样,指的是不能重写(重写赋值)。
这个方法对于Object.freeze的定义非常适用:
- function freeze
 (obj: Type): Readonly ; 
作用:构建一个对象类型,该对象类型的key来自Keys,并且其key对应的value是Type。所以这个方法非常适用于将一个类型的属性映射到另外一个类型。
示例:
- interface CatInfo {
 - age: number;
 - breed: string;
 - }
 - type CatName = "miffy" | "boris" | "mordred";
 - const cats: Record
 = { - miffy: { age: 10, breed: "Persian" },
 - boris: { age: 5, breed: "Maine Coon" },
 - mordred: { age: 16, breed: "British Shorthair" },
 - };
 - cats.boris; // (property) boris: CatInfo
 
我们看看Record背后定义。
- /**
 - * Construct a type with a set of properties K of type T
 - */
 - type Record
 = { - [P in K]: T;
 - };
 
上面涉及的新的知识点:keyof any。
我们先看一段代码:
- type A = keyof any;
 - type EqualA = string | number | symbol; // A其实等价于EqualA
 - type Is = A extends EqualA ? true : false;
 - const is: Is = false; // Type 'false' is not assignable to type 'true'.
 
因此如果我们这样使用就会提示报错了:
- interface CatInfo {
 - age: number;
 - breed: string;
 - }
 - type CatName = "miffy" | "boris" | "mordred" | false; // false导致
 - const cats: Record
 = { // Error: Type 'string | boolean' does not satisfy the constraint 'string | number | symbol'. Type 'boolean' is not assignable to type 'string | number | symbol'. - miffy: { age: 10, breed: "Persian" },
 - boris: { age: 5, breed: "Maine Coon" },
 - mordred: { age: 16, breed: "British Shorthair" },
 - };
 
Keys的类型有要求:string literal or union of string literals。
作用:构建返回一个根据Keys从类型Type拣选所需的属性的新类型。
代码示例:
- interface Todo {
 - title: string;
 - description: string;
 - completed: boolean;
 - }
 - type TodoPreview = Pick
 ; - const todo: TodoPreview = { // 只需要Keys: title and completed
 - title: "Clean room",
 - completed: false,
 - };
 - todo;
 
同样我们看看其背后的实现:这里就没有新的知识点了。
- /**
 - * From T, pick a set of properties whose keys are in the union K
 - */
 - type Pick
 = { - [P in K]: T[P];
 - };
 
这里就不重复介绍,可以看我之前文章:TypeScript学习之Omit。
作用:从Type中排除可以分配给ExcludedUnion的类型。
示例:
- type T0 = Exclude<"a" | "b" | "c", "a">; // type T0 = "b" | "c"
 - type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // type T1 = "c"
 - type T2 = Exclude
 void), Function>; // type T2 = string | number 
我们看看Exclude背后的实现:
- /**
 - * Exclude from T those types that are assignable to U
 - */
 - type Exclude
 = T extends U ? never : T; 
涉及知识点:
T extends U ? never : T这里的extends可与class的extends不是一回事,这里指的是条件类型。这里不做过多的扩展,重点通过一个概念分布式条件类型来理解上面Exclude的写法。
- type A = 'a' | 'b' | 'c';
 - type B = 'a';
 - type C = Exclude; // 'b' | 'c';
 - // A extends B ? never : A 等价于 ('a' | 'b' | 'c') extends B ? never : ('a' | 'b' | 'c') 等价于如下
 - type D = ('a' extends B ? never : 'a') | ('b' extends B ? never : 'b') | ('c' extends B ? never : 'c'); // 'b' | 'c';
 
作用:从Type中检出可以分配给Union的类型。示例:
- type T0 = Extract<"a" | "b" | "c", "a" | "f">; // type T0 = "a"
 - type T1 = Extract
 void), Function>; // type T1 = () => void 
我们看看Extract背后的定义:
- /**
 - * Extract from T those types that are assignable to U
 - */
 - type Extract
 = T extends U ? T : never; 
所有你阔以看到Extract就是跟Exclude取反的区别。
作用:排除类型Type中的null、undefined。
示例:
- type T0 = NonNullable
 ; // type T0 = string | number - type T1 = NonNullable
 ;// type T1 = string[] 
看看NonNullable的定义:
- /**
 - * Exclude null and undefined from T
 - */
 - type NonNullable
 = T extends null | undefined ? never : T; 
我们可以看到其实还是上面分布式条件类型extends的运用。
作用:基于类型Type的参数构建一个新的元组类型。示例:
- declare function f1(arg: { a: number; b: string }): void;
 - type T0 = Parameters<() => string>; // type T0 = []
 - type T1 = Parameters<(s: string) => void>; // type T1 = [s: string]
 - type T2 = Parameters<
 (arg: T) => T>; // type T2 = [arg: unknown] - type T3 = Parameters
 ; - // type T3 = [arg: {
 - // a: number;
 - // b: string;
 - // }]
 - type T4 = Parameters
 ; // type T4 = unknown[] - type T5 = Parameters
 ; // type T5 = never - type T6 = Parameters
 ; // Type 'string' does not satisfy the constraint '(...args: any) => any'. type T6 = never - type T7 = Parameters
 ; - // Type 'Function' does not satisfy the constraint '(...args: any) => any'.
 - // Type 'Function' provides no match for the signature '(...args: any): any'.
 - // type T7 = never
 
我们再看看Parameters背后实现。
- /**
 - * Obtain the parameters of a function type in a tuple
 - */
 - type Parameters
 any> = T extends (...args: infer P) => any ? P : never; 
涉及知识点:
T extends (...args: any) => any定义了Parameters的泛型约束,兼容目前所有函数的类型定义。infer P:用于表示待推断的函数参数。
T extends (...args: infer P) => any ? P : never:表示如果 T 能赋值给 (...args: infer P) => any,则结果是 (...args: infer P) => any类型中的参数为 P,否则返回为 never。
关于info更多学习推荐深入理解typescript-info。
作用:从构造函数类型 Type 的参数类型构造元组或数组类型(如果 Type 不是函数,则为 never)。示例:
- type T0 = ConstructorParameters
 ; // type T0 = [message?: string] - type T1 = ConstructorParameters
 ; // type T1 = string[] - type T2 = ConstructorParameters
 ; // type T2 = [pattern: string | RegExp, flags?: string] - type T3 = ConstructorParameters
 ; // type T3 = unknown[] 
看看其ConstructorParameters定义:
- /**
 - * Obtain the parameters of a constructor function type in a tuple
 - */
 - type ConstructorParameters
 any> = T extends abstract new (...args: infer P) => any ? P : never; 
ConstructorParameters跟Parameters的定义几乎一样,区别在于前者是表达构造函数签名的定义。
常见的构造函数类型签名有:基于Type或者Interface。
- type SomeConstructor = {
 - new (s: string): SomeObject;
 - };
 - function fn(ctor: SomeConstructor) {
 - return new ctor("hello");
 - }
 - interface CallOrConstruct {
 - new (s: string): Date;
 - (n?: number): number;
 - }
 
作用:基于函数Type的返回值类型创建一个新类型。
示例:
- declare function f1(): { a: number; b: string };
 - type T0 = ReturnType<() => string>; // type T0 = string
 - type T4 = ReturnType
 ; - // type T4 = {
 - // a: number;
 - // b: string;
 - // }
 
源码定义:
- /**
 - * Obtain the return type of a function type
 - */
 - type ReturnType
 any> = T extends (...args: any) => infer R ? R : any; 
我们可以看到其原理跟前几个差不多,区别在于infer推断的位置不同。
作用:基于函数类型Type的constructor的类型构造一个新类型。示例:
- class C {
 - x = 0;
 - y = 0;
 - }
 - type T0 = InstanceType
 ; // type T0 = C - type T1 = InstanceType
 ; // type T1 = any 
源码定义:
- /**
 - * Obtain the return type of a constructor function type
 - */
 - type InstanceType
 any> = T extends abstract new (...args: any) => infer R ? R : any; 
通过对比发现:InstanceType 与 ReturnType 的区别是它多了函数构造签名定义,与 ConstructorParameters 的区别是它推断的不是参数类型,而是返回值类型。
作用:获取函数类型Type中的this类型。如果没有返回unknown。
- function toHex(this: Number) {
 - return this.toString(16);
 - }
 - function numberToString(n: ThisParameterType
 ) { // n: number - return toHex.apply(n);
 - }
 
源码定义:
- /**
 - * 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; 
如果想了解如何在函数中定义this,建议还是看官网。
作用:移除函数类型Type中参数的this。
示例:
- function toHex(this: Number) {
 - return this.toString(16);
 - }
 - const fiveToHex: OmitThisParameter
 = toHex.bind(5); // const fiveToHex: () => string - console.log(fiveToHex());
 
源码定义:
- /**
 - * 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; 
unknown extends ThisParameterType
                本文题目:TypeScript学习之UtilityTypes
                
                链接地址:http://www.csdahua.cn/qtweb/news33/4883.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网