日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
TypeScript學(xué)習(xí)之UtilityTypes

本文轉(zhuǎn)載自微信公眾號(hào)「xyz編程日記」,作者小綜哥 。轉(zhuǎn)載本文請(qǐng)聯(lián)系xyz編程日記公眾號(hào)。

為平谷等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及平谷網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、平谷網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!

 TypeScript學(xué)習(xí)之Utility Types

TS在全局內(nèi)置了很多Utility Types,可以極大的提高我們開發(fā)效率。所以本文就是詳細(xì)介紹、理解、掌握。

Partial

作用:它會(huì)將Type內(nèi)所有屬性置為可選,返回一個(gè)給定類型Type的子集。

示例:

 
 
 
  1. interface Todo { 
  2.   title: string; 
  3.   description: string; 
  4.  
  5. // 場(chǎng)景:只想更新toTo部分屬性,Partial的使用就比較優(yōu)雅了 
  6. function updateTodo(todo: Todo, fieldsToUpdate: Partial) { 
  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背后是如何實(shí)現(xiàn)的:

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

上面定義涉及的知識(shí)點(diǎn):

  • 泛型
  • keyof運(yùn)算符:獲取T的所有鍵
  • [P in keyof T]:遍歷T的所有key,映射類型、索引簽名
  • ?:可選

Required

作用:Required與上面的Partial相反,構(gòu)建返回一個(gè)Type的所有屬性為必選的新類型。

示例:

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

我們看看Required背后的實(shí)現(xiàn):

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

上面定義涉及的知識(shí)點(diǎn):

在TS2.8版本改善了對(duì)映射類型修飾符的支持。

在TS2.8版本之前,支持對(duì)映射類型的屬性添加readonly、?的修飾符,但是并沒(méi)有提供移除修飾符的能力。默認(rèn)它的修飾符是跟映射類型保持一致的,有興趣的可以看這個(gè)PR以及它fix的issue。那現(xiàn)在映射類型它支持通過(guò)+或者-來(lái)添加or移除readonly或者?修飾符。

我們看一個(gè)示例:

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

到這里我們就理解-?的含義了。

Readonly

作用:將Type所有屬性置為只讀。示例:

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

我們看看Readonly背后的實(shí)現(xiàn):

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

這里有上面的知識(shí)鋪墊就比較好理解了,只需要知道映射類型支持修飾符readonly、?。

另外這里補(bǔ)充下readonly的含義跟JS的const不能修改的含義一樣,指的是不能重寫(重寫賦值)。

這個(gè)方法對(duì)于Object.freeze的定義非常適用:

 
 
 
  1. function freeze(obj: Type): Readonly

Record

作用:構(gòu)建一個(gè)對(duì)象類型,該對(duì)象類型的key來(lái)自Keys,并且其key對(duì)應(yīng)的value是Type。所以這個(gè)方法非常適用于將一個(gè)類型的屬性映射到另外一個(gè)類型。

示例:

 
 
 
  1. interface CatInfo { 
  2.   age: number; 
  3.   breed: string; 
  4.   
  5. type CatName = "miffy" | "boris" | "mordred"; 
  6.   
  7. const cats: Record = { 
  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 = { 
  5.     [P in K]: T; 
  6. }; 

上面涉及的新的知識(shí)點(diǎn):keyof any。

我們先看一段代碼:

 
 
 
  1. type A = keyof any; 
  2.  
  3. type EqualA = string | number | symbol; // A其實(shí)等價(jià)于EqualA 
  4.  
  5. type Is = A extends EqualA ? true : false; 
  6.  
  7. const is: Is = false; // Type 'false' is not assignable to type 'true'. 

因此如果我們這樣使用就會(huì)提示報(bào)錯(cuò)了:

 
 
 
  1. interface CatInfo { 
  2.   age: number; 
  3.   breed: string; 
  4.   
  5. type CatName = "miffy" | "boris" | "mordred" | false; // false導(dǎo)致 
  6.   
  7. 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'. 
  8.   miffy: { age: 10, breed: "Persian" }, 
  9.   boris: { age: 5, breed: "Maine Coon" }, 
  10.   mordred: { age: 16, breed: "British Shorthair" }, 
  11. }; 

Pick

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

作用:構(gòu)建返回一個(gè)根據(jù)Keys從類型Type揀選所需的屬性的新類型。

代碼示例:

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

同樣我們看看其背后的實(shí)現(xiàn):這里就沒(méi)有新的知識(shí)點(diǎn)了。

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

Omit

這里就不重復(fù)介紹,可以看我之前文章:TypeScript學(xué)習(xí)之Omit。

Exclude

作用:從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 void), Function>; // type T2 = string | number 

我們看看Exclude背后的實(shí)現(xiàn):

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

涉及知識(shí)點(diǎn):

T extends U ? never : T這里的extends可與class的extends不是一回事,這里指的是條件類型。這里不做過(guò)多的擴(kuò)展,重點(diǎn)通過(guò)一個(gè)概念分布式條件類型來(lái)理解上面Exclude的寫法。

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

Extract

作用:從Type中檢出可以分配給Union的類型。示例:

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

我們看看Extract背后的定義:

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

所有你闊以看到Extract就是跟Exclude取反的區(qū)別。

NonNullable

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

示例:

 
 
 
  1. type T0 = NonNullable; // type T0 = string | number 
  2. type T1 = NonNullable;// type T1 = string[] 

看看NonNullable的定義:

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

我們可以看到其實(shí)還是上面分布式條件類型extends的運(yùn)用。

Parameters

作用:基于類型Type的參數(shù)構(gòu)建一個(gè)新的元組類型。示例:

 
 
 
  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<(arg: T) => T>; // type T2 = [arg: unknown] 
  6. type T3 = Parameters
  7.       
  8. // type T3 = [arg: { 
  9. //     a: number; 
  10. //     b: string; 
  11. // }] 
  12. type T4 = Parameters; // type T4 = unknown[] 
  13. type T5 = Parameters; // type T5 = never 
  14. type T6 = Parameters; // Type 'string' does not satisfy the constraint '(...args: any) => any'. type T6 = never 
  15. type T7 = Parameters
  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 

我們?cè)倏纯碢arameters背后實(shí)現(xiàn)。

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

涉及知識(shí)點(diǎn):

T extends (...args: any) => any定義了Parameters的泛型約束,兼容目前所有函數(shù)的類型定義。infer P:用于表示待推斷的函數(shù)參數(shù)。

T extends (...args: infer P) => any ? P : never:表示如果 T 能賦值給 (...args: infer P) => any,則結(jié)果是 (...args: infer P) => any類型中的參數(shù)為 P,否則返回為 never。

關(guān)于info更多學(xué)習(xí)推薦深入理解typescript-info。

ConstructorParameters

作用:從構(gòu)造函數(shù)類型 Type 的參數(shù)類型構(gòu)造元組或數(shù)組類型(如果 Type 不是函數(shù),則為 never)。示例:

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

看看其ConstructorParameters定義:

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

ConstructorParameters跟Parameters的定義幾乎一樣,區(qū)別在于前者是表達(dá)構(gòu)造函數(shù)簽名的定義。

常見(jiàn)的構(gòu)造函數(shù)類型簽名有:基于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

作用:基于函數(shù)Type的返回值類型創(chuàng)建一個(gè)新類型。

示例:

 
 
 
  1. declare function f1(): { a: number; b: string }; 
  2.   
  3. type T0 = ReturnType<() => string>; // type T0 = string 
  4. type T4 = ReturnType
  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 any> = T extends (...args: any) => infer R ? R : any; 

我們可以看到其原理跟前幾個(gè)差不多,區(qū)別在于infer推斷的位置不同。

InstanceType

作用:基于函數(shù)類型Type的constructor的類型構(gòu)造一個(gè)新類型。示例:

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

源碼定義:

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

通過(guò)對(duì)比發(fā)現(xiàn):InstanceType 與 ReturnType 的區(qū)別是它多了函數(shù)構(gòu)造簽名定義,與 ConstructorParameters 的區(qū)別是它推斷的不是參數(shù)類型,而是返回值類型。

ThisParameterType

作用:獲取函數(shù)類型Type中的this類型。如果沒(méi)有返回unknown。

 
 
 
  1. function toHex(this: Number) { 
  2.   return this.toString(16); 
  3.   
  4. function numberToString(n: ThisParameterType) { // 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 extends (this: infer U, ...args: any[]) => any ? U : unknown; 

如果想了解如何在函數(shù)中定義this,建議還是看官網(wǎng)。

OmitThisParameter

作用:移除函數(shù)類型Type中參數(shù)的this。

示例:

 
 
 
  1. function toHex(this: Number) { 
  2.   return this.toString(16); 
  3.   
  4. const fiveToHex: OmitThisParameter = 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 = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; 

unknown extends ThisParameterType:如果T函數(shù)參數(shù)中沒(méi)有this,則直接返回T。否則,T extends (...args: infer A) => infer R ? (...args: A) => R : T;,如果T是后者的子類型,那么返回新的函數(shù),函數(shù)參數(shù)為推導(dǎo)的infer A,返回值為infer R。否則返回T。

ending

  • 參考官網(wǎng)。

當(dāng)前標(biāo)題:TypeScript學(xué)習(xí)之UtilityTypes
本文地址:
http://www.dlmjj.cn/article/dpjopgs.html