TypeScript学习之Utility Types

开发 前端
TS在全局内置了很多Utility Types,可以极大的提高我们开发效率。所以本文就是详细介绍、理解、掌握。

[[419655]]

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

 TypeScript学习之Utility Types

TS在全局内置了很多Utility Types,可以极大的提高我们开发效率。所以本文就是详细介绍、理解、掌握。

Partial<Type>

作用:它会将Type内所有属性置为可选,返回一个给定类型Type的子集。

示例:

  1. interface Todo { 
  2.   title: string; 
  3.   description: string; 
  4.  
  5. // 场景:只想更新toTo部分属性,Partial的使用就比较优雅了 
  6. function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { 
  7.   return { ...todo, ...fieldsToUpdate }; 
  8.   
  9. const todo1 = { 
  10.   title: "organize desk"
  11.   description: "clear clutter"
  12. }; 
  13.   
  14. const todo2 = updateTodo(todo1, { 
  15.   description: "throw out trash"
  16. }); 

我们看看Partial背后是如何实现的:

  1. /** 
  2.  * Make all properties in T optional 
  3.  */ 
  4. type Partial<T> = { 
  5.     [P in keyof T]?: T[P]; 
  6. }; 

上面定义涉及的知识点:

  • 泛型<T>
  • keyof运算符:获取T的所有键
  • [P in keyof T]:遍历T的所有key,映射类型、索引签名
  • ?:可选

Required<Type>

作用:Required与上面的Partial相反,构建返回一个Type的所有属性为必选的新类型。

示例:

  1. interface Props { 
  2.   a?: number; 
  3.   b?: string; 
  4.   
  5. const obj: Props = { a: 5 }; 
  6.   
  7. const obj2: Required<Props> = { a: 5 }; // Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'

我们看看Required背后的实现:

  1. /** 
  2.  * Make all properties in T required 
  3.  */ 
  4. type Required<T> = { 
  5.     [P in keyof T]-?: T[P]; 
  6. }; 

上面定义涉及的知识点:

在TS2.8版本改善了对映射类型修饰符的支持。

在TS2.8版本之前,支持对映射类型的属性添加readonly、?的修饰符,但是并没有提供移除修饰符的能力。默认它的修饰符是跟映射类型保持一致的,有兴趣的可以看这个PR以及它fix的issue。那现在映射类型它支持通过+或者-来添加or移除readonly或者?修饰符。

我们看一个示例:

  1. type A = { readonly a? : number, b: string }; 
  2. type MockRequired<T> = { 
  3.     -readonly [P in keyof T]-?: T[P] // 这里可以不需要-? 
  4. }; 
  5.  
  6. const test: MockRequired<A> = { //  我希望a是必须的 
  7.     a: 10, 
  8.     b: 'b' 
  9. }; 
  10.  
  11. test.a = 20; // 我希望可以修改a 

到这里我们就理解-?的含义了。

Readonly<Type>

作用:将Type所有属性置为只读。示例:

  1. interface Todo { 
  2.   title: string; 
  3.   
  4. const todo: Readonly<Todo> = { 
  5.   title: "Delete inactive users"
  6. }; 
  7.   
  8. todo.title = "Hello"; // Cannot assign to 'title' because it is a read-only property. 

我们看看Readonly背后的实现:

  1. /** 
  2.  * Make all properties in T readonly 
  3.  */ 
  4. type Readonly<T> = { 
  5.     readonly [P in keyof T]: T[P]; 
  6. }; 

这里有上面的知识铺垫就比较好理解了,只需要知道映射类型支持修饰符readonly、?。

另外这里补充下readonly的含义跟JS的const不能修改的含义一样,指的是不能重写(重写赋值)。

这个方法对于Object.freeze的定义非常适用:

  1. function freeze<Type>(obj: Type): Readonly<Type>; 

Record<Keys,Type>

作用:构建一个对象类型,该对象类型的key来自Keys,并且其key对应的value是Type。所以这个方法非常适用于将一个类型的属性映射到另外一个类型。

示例:

  1. interface CatInfo { 
  2.   age: number; 
  3.   breed: string; 
  4.   
  5. type CatName = "miffy" | "boris" | "mordred"
  6.   
  7. const cats: Record<CatName, CatInfo> = { 
  8.   miffy: { age: 10, breed: "Persian" }, 
  9.   boris: { age: 5, breed: "Maine Coon" }, 
  10.   mordred: { age: 16, breed: "British Shorthair" }, 
  11. }; 
  12.   
  13. cats.boris; // (property) boris: CatInfo 

我们看看Record背后定义。

  1. /** 
  2.  * Construct a type with a set of properties K of type T 
  3.  */ 
  4. type Record<K extends keyof any, T> = { 
  5.     [P in K]: T; 
  6. }; 

上面涉及的新的知识点:keyof any。

我们先看一段代码:

  1. type A = keyof any
  2.  
  3. type EqualA = string | number | symbol; // A其实等价于EqualA 
  4.  
  5. type Is = A extends EqualA ? true : false
  6.  
  7. const isIs = false; // Type 'false' is not assignable to type 'true'

因此如果我们这样使用就会提示报错了:

  1. interface CatInfo { 
  2.   age: number; 
  3.   breed: string; 
  4.   
  5. type CatName = "miffy" | "boris" | "mordred" | false; // false导致 
  6.   
  7. const cats: Record<CatName, CatInfo> = { // Error: Type 'string | boolean' does not satisfy the constraint 'string | number | symbol'. Type 'boolean' is not assignable to type 'string | number | symbol'
  8.   miffy: { age: 10, breed: "Persian" }, 
  9.   boris: { age: 5, breed: "Maine Coon" }, 
  10.   mordred: { age: 16, breed: "British Shorthair" }, 
  11. }; 

Pick<Type, Keys>

Keys的类型有要求:string literal or union of string literals。

作用:构建返回一个根据Keys从类型Type拣选所需的属性的新类型。

代码示例:

  1. interface Todo { 
  2.   title: string; 
  3.   description: string; 
  4.   completed: boolean; 
  5.   
  6. type TodoPreview = Pick<Todo, "title" | "completed">; 
  7.   
  8. const todo: TodoPreview = { // 只需要Keys: title and completed 
  9.   title: "Clean room"
  10.   completed: false
  11. }; 
  12.   
  13. todo; 

同样我们看看其背后的实现:这里就没有新的知识点了。

  1. /** 
  2.  * From T, pick a set of properties whose keys are in the union K 
  3.  */ 
  4. type Pick<T, K extends keyof T> = { 
  5.     [P in K]: T[P]; 
  6. }; 

Omit<Type, Keys>

这里就不重复介绍,可以看我之前文章:TypeScript学习之Omit。

Exclude<Type, ExcludedUnion>

作用:从Type中排除可以分配给ExcludedUnion的类型。

示例:

  1. type T0 = Exclude<"a" | "b" | "c""a">; // type T0 = "b" | "c" 
  2. type T1 = Exclude<"a" | "b" | "c""a" | "b">;  // type T1 = "c" 
  3. type T2 = Exclude<string | number | (() => void), Function>; // type T2 = string | number 

我们看看Exclude背后的实现:

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

涉及知识点:

T extends U ? never : T这里的extends可与class的extends不是一回事,这里指的是条件类型。这里不做过多的扩展,重点通过一个概念分布式条件类型来理解上面Exclude的写法。

  1. type A = 'a' | 'b' | 'c'
  2. type B = 'a'
  3.  
  4. type C = Exclude<A, B>; // 'b' | 'c'
  5.  
  6. // A extends B ? never : A 等价于 ('a' | 'b' | 'c') extends B ? never : ('a' | 'b' | 'c') 等价于如下 
  7. type D = ('a' extends B ? never : 'a') | ('b' extends B ? never : 'b') | ('c' extends B ? never : 'c'); // 'b' | 'c'

Extract<Type, Union>

作用:从Type中检出可以分配给Union的类型。示例:

  1. type T0 = Extract<"a" | "b" | "c""a" | "f">; // type T0 = "a" 
  2. type T1 = Extract<string | number | (() => void), Function>; // type T1 = () => void 

我们看看Extract背后的定义:

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

所有你阔以看到Extract就是跟Exclude取反的区别。

NonNullable<Type>

作用:排除类型Type中的null、undefined。

示例:

  1. type T0 = NonNullable<string | number | undefined>; // type T0 = string | number 
  2. type T1 = NonNullable<string[] | null | undefined>;// type T1 = string[] 

看看NonNullable的定义:

  1. /** 
  2.  * Exclude null and undefined from T 
  3.  */ 
  4. type NonNullable<T> = T extends null | undefined ? never : T; 

我们可以看到其实还是上面分布式条件类型extends的运用。

Parameters<Type>

作用:基于类型Type的参数构建一个新的元组类型。示例:

  1. declare function f1(arg: { a: number; b: string }): void; 
  2.   
  3. type T0 = Parameters<() => string>; // type T0 = [] 
  4. type T1 = Parameters<(s: string) => void>; // type T1 = [s: string] 
  5. type T2 = Parameters<<T>(arg: T) => T>; // type T2 = [arg: unknown] 
  6. type T3 = Parameters<typeof f1>; 
  7.       
  8. // type T3 = [arg: { 
  9. //     a: number; 
  10. //     b: string; 
  11. // }] 
  12. type T4 = Parameters<any>; // type T4 = unknown[] 
  13. type T5 = Parameters<never>; // type T5 = never 
  14. type T6 = Parameters<string>; // Type 'string' does not satisfy the constraint '(...args: any) => any'. type T6 = never 
  15. type T7 = Parameters<Function>; 
  16. // Type 'Function' does not satisfy the constraint '(...args: any) => any'
  17. //   Type 'Function' provides no match for the signature '(...args: any): any'
  18.       
  19. // type T7 = never 

我们再看看Parameters背后实现。

  1. /** 
  2.  * Obtain the parameters of a function type in a tuple 
  3.  */ 
  4. type Parameters<T extends (...args: any) => 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。

ConstructorParameters<Type>

作用:从构造函数类型 Type 的参数类型构造元组或数组类型(如果 Type 不是函数,则为 never)。示例:

  1. type T0 = ConstructorParameters<ErrorConstructor>; // type T0 = [message?: string] 
  2. type T1 = ConstructorParameters<FunctionConstructor>; // type T1 = string[] 
  3. type T2 = ConstructorParameters<RegExpConstructor>; // type T2 = [pattern: string | RegExp, flags?: string] 
  4. type T3 = ConstructorParameters<any>; // type T3 = unknown[] 

看看其ConstructorParameters定义:

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

ConstructorParameters跟Parameters的定义几乎一样,区别在于前者是表达构造函数签名的定义。

常见的构造函数类型签名有:基于Type或者Interface。

  1. type SomeConstructor = { 
  2.   new (s: string): SomeObject; 
  3. }; 
  4. function fn(ctor: SomeConstructor) { 
  5.   return new ctor("hello"); 
  6.  
  7. interface CallOrConstruct { 
  8.   new (s: string): Date
  9.   (n?: number): number; 

ReturnType<Type>

作用:基于函数Type的返回值类型创建一个新类型。

示例:

  1. declare function f1(): { a: number; b: string }; 
  2.   
  3. type T0 = ReturnType<() => string>; // type T0 = string 
  4. type T4 = ReturnType<typeof f1>; 
  5.  
  6. // type T4 = { 
  7. //     a: number; 
  8. //     b: string; 
  9. // } 

源码定义:

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

我们可以看到其原理跟前几个差不多,区别在于infer推断的位置不同。

InstanceType<Type>

作用:基于函数类型Type的constructor的类型构造一个新类型。示例:

  1. class C { 
  2.   x = 0; 
  3.   y = 0; 
  4.   
  5. type T0 = InstanceType<typeof C>; // type T0 = C 
  6.  
  7. type T1 = InstanceType<any>; // type T1 = any 

源码定义:

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

通过对比发现:InstanceType 与 ReturnType 的区别是它多了函数构造签名定义,与 ConstructorParameters 的区别是它推断的不是参数类型,而是返回值类型。

ThisParameterType<Type>

作用:获取函数类型Type中的this类型。如果没有返回unknown。

  1. function toHex(this: Number) { 
  2.   return this.toString(16); 
  3.   
  4. function numberToString(n: ThisParameterType<typeof toHex>) { // n: number 
  5.   return toHex.apply(n); 

源码定义:

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

如果想了解如何在函数中定义this,建议还是看官网。

OmitThisParameter<Type>

作用:移除函数类型Type中参数的this。

示例:

  1. function toHex(this: Number) { 
  2.   return this.toString(16); 
  3.   
  4. const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5); // const fiveToHex: () => string 
  5.   
  6. console.log(fiveToHex()); 

源码定义:

  1. /** 
  2.  * Removes the 'this' parameter from a function type. 
  3.  */ 
  4. type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; 

unknown extends ThisParameterType<T>:如果T函数参数中没有this,则直接返回T。否则,T extends (...args: infer A) => infer R ? (...args: A) => R : T;,如果T是后者的子类型,那么返回新的函数,函数参数为推导的infer A,返回值为infer R。否则返回T。

ending

  • 参考官网。

 

责任编辑:武晓燕 来源: xyz编程日记
相关推荐

2022-02-22 13:50:01

TypeScrip前端框架

2022-02-23 08:50:37

MySQL

2020-08-11 11:20:30

Typescript设计模式

2022-06-20 08:50:16

TypeScript类型语法

2022-09-30 08:31:06

TypeScriptJavaScrip

2021-06-05 21:30:24

typescriptOverride检查

2010-01-05 13:31:44

Windows 7安装盘制作

2019-12-09 10:02:41

泛型ypeScript前端

2022-02-21 16:11:16

TypeScript构造函数

2022-11-27 21:54:34

TypeScrip开发Github

2020-03-23 09:31:51

JavaScript函数技术

2014-04-09 16:16:56

System Imag镜像

2021-09-15 07:56:33

函数类型Go

2017-11-24 10:43:43

Madlib机器学习

2022-03-10 15:42:18

机器学习GitHub

2016-10-11 13:32:50

函数式TypeScriptJavascript

2020-11-06 09:00:00

机器学习集成学习人工智能

2011-08-01 18:27:58

iPhone开发 UISearchBa

2011-03-08 16:30:24

Proftpd

2009-12-17 16:16:00

CCIE学习
点赞
收藏

51CTO技术栈公众号