新聞中心
本文轉(zhuǎn)載自微信公眾號「xyz編程日記」,作者小綜哥 。轉(zhuǎn)載本文請聯(lián)系xyz編程日記公眾號。

為平谷等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及平谷網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、平谷網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
TypeScript學(xué)習(xí)之Utility Types
TS在全局內(nèi)置了很多Utility Types,可以極大的提高我們開發(fā)效率。所以本文就是詳細介紹、理解、掌握。
Partial
作用:它會將Type內(nèi)所有屬性置為可選,返回一個給定類型Type的子集。
示例:
- interface Todo {
- title: string;
- description: string;
- }
- // 場景:只想更新toTo部分屬性,Partial的使用就比較優(yōu)雅了
- 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背后是如何實現(xiàn)的:
- /**
- * Make all properties in T optional
- */
- type Partial
= { - [P in keyof T]?: T[P];
- };
上面定義涉及的知識點:
- 泛型
- keyof運算符:獲取T的所有鍵
- [P in keyof T]:遍歷T的所有key,映射類型、索引簽名
- ?:可選
Required
作用:Required與上面的Partial相反,構(gòu)建返回一個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背后的實現(xiàn):
- /**
- * Make all properties in T required
- */
- type Required
= { - [P in keyof T]-?: T[P];
- };
上面定義涉及的知識點:
在TS2.8版本改善了對映射類型修飾符的支持。
在TS2.8版本之前,支持對映射類型的屬性添加readonly、?的修飾符,但是并沒有提供移除修飾符的能力。默認它的修飾符是跟映射類型保持一致的,有興趣的可以看這個PR以及它fix的issue。那現(xiàn)在映射類型它支持通過+或者-來添加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
到這里我們就理解-?的含義了。
Readonly
作用:將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背后的實現(xiàn):
- /**
- * 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 ;
Record
作用:構(gòu)建一個對象類型,該對象類型的key來自Keys,并且其key對應(yīng)的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導(dǎo)致
- 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" },
- };
Pick
Keys的類型有要求:string literal or union of string literals。
作用:構(gòu)建返回一個根據(jù)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;
同樣我們看看其背后的實現(xiàn):這里就沒有新的知識點了。
- /**
- * From T, pick a set of properties whose keys are in the union K
- */
- type Pick
= { - [P in K]: T[P];
- };
Omit
這里就不重復(fù)介紹,可以看我之前文章:TypeScript學(xué)習(xí)之Omit。
Exclude
作用:從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背后的實現(xiàn):
- /**
- * 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';
Extract
作用:從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取反的區(qū)別。
NonNullable
作用:排除類型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的運用。
Parameters
作用:基于類型Type的參數(shù)構(gòu)建一個新的元組類型。示例:
- 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背后實現(xiàn)。
- /**
- * 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的泛型約束,兼容目前所有函數(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)。示例:
- 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的定義幾乎一樣,區(qū)別在于前者是表達構(gòu)造函數(shù)簽名的定義。
常見的構(gòu)造函數(shù)類型簽名有:基于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;
- }
ReturnType
作用:基于函數(shù)Type的返回值類型創(chuàng)建一個新類型。
示例:
- 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;
我們可以看到其原理跟前幾個差不多,區(qū)別在于infer推斷的位置不同。
InstanceType
作用:基于函數(shù)類型Type的constructor的類型構(gòu)造一個新類型。示例:
- 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;
通過對比發(fā)現(xiàn):InstanceType 與 ReturnType 的區(qū)別是它多了函數(shù)構(gòu)造簽名定義,與 ConstructorParameters 的區(qū)別是它推斷的不是參數(shù)類型,而是返回值類型。
ThisParameterType
作用:獲取函數(shù)類型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;
如果想了解如何在函數(shù)中定義this,建議還是看官網(wǎng)。
OmitThisParameter
作用:移除函數(shù)類型Type中參數(shù)的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
ending
- 參考官網(wǎng)。
網(wǎng)頁名稱:TypeScript學(xué)習(xí)之UtilityTypes
網(wǎng)頁URL:http://fisionsoft.com.cn/article/dpjopgs.html


咨詢
建站咨詢
