
英文 | https://javascript.plainenglish.io/15-utility-types-that-every-typescript-developer-should-know-6cf121d4047c
我們在使用 TypeScript 的過程中,我們是面向類型編程的,為了滿足不同的工作場景,我們需要對已知類型進行改造。為了方便 TypeScript 用戶,TypeScript 開發團隊為我們提供了許多有用的內置實用程序類型。通過這些實用類型,我們可以輕鬆地轉換類型、提取類型、排除類型,或者獲取函數的參數類型或返回值類型。在本文中,我從 TypeScript 的內置實用程序類型中挑選了 15 種非常有用的類型,並以圖像的形式介紹了它們的用法和內部工作原理,看完這篇文章,相信你可以真正掌握這些內置實用程序類型的用法。構造一個類型,其中 Type 的所有屬性都設置為可選。
/** * Make all properties in T optional. * typescript/lib/lib.es5.d.ts */type Partial<T> = { [P in keyof T]?: T[P];};
構造一個類型,該類型由設置為 required Type 的所有屬性組成,部分的反義詞。
/** * Make all properties in T required. * typescript/lib/lib.es5.d.ts */type Required<T> = { [P in keyof T]-?: T[P];};
構造一個 Type 的所有屬性都設置為 readonly 的類型,這意味着構造類型的屬性不能被重新分配。
/** * Make all properties in T readonly. * typescript/lib/lib.es5.d.ts */type Readonly<T> = { readonly [P in keyof T]: T[P];};
構造一個對象類型,其屬性鍵為 Keys,其屬性值為 Type,此實用程序可用於將一種類型的屬性映射到另一種類型。
/** * Construct a type with a set of properties K of type T. * typescript/lib/lib.es5.d.ts */type Record<K extends keyof any, T> = { [P in K]: T;};5. Exclude<UnionType, ExcludedMembers>通過從 UnionType 中排除可分配給 ExcludedMembers 的所有聯合成員來構造類型。
/** * Exclude from T those types that are assignable to U. * typescript/lib/lib.es5.d.ts */type Exclude<T, U> = T extends U ? never : T;
通過從 Type 中提取所有可分配給 Union 的聯合成員來構造一個類型。
/** * Extract from T those types that are assignable to U. * typescript/lib/lib.es5.d.ts */type Extract<T, U> = T extends U ? T : never;
通過從 Type 中選擇一組屬性 Keys(字符串文字或字符串文字的聯合)來構造一個類型。
/** * From T, pick a set of properties whose keys are in the union K. * typescript/lib/lib.es5.d.ts */type Pick<T, K extends keyof T> = { [P in K]: T[P];};
通過從 Type 中選擇所有屬性然後刪除 Keys(字符串文字或字符串文字的聯合)來構造一個類型。
/** * Construct a type with the properties of T except for those * in type K. * typescript/lib/lib.es5.d.ts */type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
通過從 Type 中排除 null 和 undefined 來構造一個類型。
/** * Exclude null and undefined from T. * typescript/lib/lib.es5.d.ts */type NonNullable<T> = T extends null | undefined ? never : T;從函數類型 Type 的參數中使用的類型構造元組類型。
/** * Obtain the parameters of a function type in a tuple. * typescript/lib/lib.es5.d.ts */type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
/** * Obtain the return type of a function type. * typescript/lib/lib.es5.d.ts */type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;12. Uppercase<StringType>



除了上述這些實用程序類型之外,還有一些其他常用的 TypeScript 內置實用程序類型,具體如下:ConstructorParameters<Type>:根據構造函數類型的類型構造元組或數組類型。它產生一個包含所有參數類型的元組類型(如果 Type 不是函數,則類型 never )。InstanceType<Type>:構造一個由Type中構造函數的實例類型組成的類型。ThisParameterType<Type>:為函數類型提取此參數的類型,如果函數類型沒有此參數,則為未知。本文介紹的實用程序類型在內部使用了有關映射類型、條件類型和推斷類型推斷的知識。如果你對映射類型和條件類型不熟悉,後面我將繼續分享一些這個方面的知識。學習更多技能
請點擊下方公眾號


