TypeScript學習之Utility Types
本文轉載自微信公眾號「xyz編程日記」,作者小綜哥 。轉載本文請聯系xyz編程日記公眾號。
TypeScript學習之Utility Types
TS在全局內置了很多Utility Types,可以極大的提高我們開發效率。所以本文就是詳細介紹、理解、掌握。
Partial<Type>
作用:它會將Type內所有屬性置為可選,返回一個給定類型Type的子集。
示例:
- interface Todo {
- title: string;
- description: string;
- }
- // 場景:只想更新toTo部分屬性,Partial的使用就比較優雅了
- function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
- 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<T> = {
- [P in keyof T]?: T[P];
- };
上面定義涉及的知識點:
- 泛型<T>
- keyof運算符:獲取T的所有鍵
- [P in keyof T]:遍歷T的所有key,映射類型、索引簽名
- ?:可選
Required<Type>
作用:Required與上面的Partial相反,構建返回一個Type的所有屬性為必選的新類型。
示例:
- interface Props {
- a?: number;
- b?: string;
- }
- const obj: Props = { a: 5 };
- const obj2: Required<Props> = { a: 5 }; // Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
我們看看Required背后的實現:
- /**
- * Make all properties in T required
- */
- type Required<T> = {
- [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<T> = {
- -readonly [P in keyof T]-?: T[P] // 這里可以不需要-?
- };
- const test: MockRequired<A> = { // 我希望a是必須的
- a: 10,
- b: 'b'
- };
- test.a = 20; // 我希望可以修改a
到這里我們就理解-?的含義了。
Readonly<Type>
作用:將Type所有屬性置為只讀。示例:
- interface Todo {
- title: string;
- }
- const todo: Readonly<Todo> = {
- 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<T> = {
- readonly [P in keyof T]: T[P];
- };
這里有上面的知識鋪墊就比較好理解了,只需要知道映射類型支持修飾符readonly、?。
另外這里補充下readonly的含義跟JS的const不能修改的含義一樣,指的是不能重寫(重寫賦值)。
這個方法對于Object.freeze的定義非常適用:
- function freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys,Type>
作用:構建一個對象類型,該對象類型的key來自Keys,并且其key對應的value是Type。所以這個方法非常適用于將一個類型的屬性映射到另外一個類型。
示例:
- interface CatInfo {
- age: number;
- breed: string;
- }
- type CatName = "miffy" | "boris" | "mordred";
- const cats: Record<CatName, CatInfo> = {
- 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<K extends keyof any, T> = {
- [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<CatName, CatInfo> = { // 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<Type, Keys>
Keys的類型有要求:string literal or union of string literals。
作用:構建返回一個根據Keys從類型Type揀選所需的屬性的新類型。
代碼示例:
- interface Todo {
- title: string;
- description: string;
- completed: boolean;
- }
- type TodoPreview = Pick<Todo, "title" | "completed">;
- 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<T, K extends keyof T> = {
- [P in K]: T[P];
- };
Omit<Type, Keys>
這里就不重復介紹,可以看我之前文章:TypeScript學習之Omit。
Exclude<Type, ExcludedUnion>
作用:從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<string | number | (() => void), Function>; // type T2 = string | number
我們看看Exclude背后的實現:
- /**
- * Exclude from T those types that are assignable to U
- */
- type Exclude<T, U> = 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<A, B>; // '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中檢出可以分配給Union的類型。示例:
- type T0 = Extract<"a" | "b" | "c", "a" | "f">; // type T0 = "a"
- type T1 = Extract<string | number | (() => void), Function>; // type T1 = () => void
我們看看Extract背后的定義:
- /**
- * Extract from T those types that are assignable to U
- */
- type Extract<T, U> = T extends U ? T : never;
所有你闊以看到Extract就是跟Exclude取反的區別。
NonNullable<Type>
作用:排除類型Type中的null、undefined。
示例:
- type T0 = NonNullable<string | number | undefined>; // type T0 = string | number
- type T1 = NonNullable<string[] | null | undefined>;// type T1 = string[]
看看NonNullable的定義:
- /**
- * Exclude null and undefined from T
- */
- type NonNullable<T> = T extends null | undefined ? never : T;
我們可以看到其實還是上面分布式條件類型extends的運用。
Parameters<Type>
作用:基于類型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<<T>(arg: T) => T>; // type T2 = [arg: unknown]
- type T3 = Parameters<typeof f1>;
- // type T3 = [arg: {
- // a: number;
- // b: string;
- // }]
- type T4 = Parameters<any>; // type T4 = unknown[]
- type T5 = Parameters<never>; // type T5 = never
- type T6 = Parameters<string>; // Type 'string' does not satisfy the constraint '(...args: any) => any'. type T6 = never
- type T7 = Parameters<Function>;
- // 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<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)。示例:
- type T0 = ConstructorParameters<ErrorConstructor>; // type T0 = [message?: string]
- type T1 = ConstructorParameters<FunctionConstructor>; // type T1 = string[]
- type T2 = ConstructorParameters<RegExpConstructor>; // type T2 = [pattern: string | RegExp, flags?: string]
- type T3 = ConstructorParameters<any>; // type T3 = unknown[]
看看其ConstructorParameters定義:
- /**
- * Obtain the parameters of a constructor function type in a tuple
- */
- type ConstructorParameters<T extends abstract new (...args: any) => 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;
- }
ReturnType<Type>
作用:基于函數Type的返回值類型創建一個新類型。
示例:
- declare function f1(): { a: number; b: string };
- type T0 = ReturnType<() => string>; // type T0 = string
- type T4 = ReturnType<typeof f1>;
- // type T4 = {
- // a: number;
- // b: string;
- // }
源碼定義:
- /**
- * Obtain the return type of a function type
- */
- type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
我們可以看到其原理跟前幾個差不多,區別在于infer推斷的位置不同。
InstanceType<Type>
作用:基于函數類型Type的constructor的類型構造一個新類型。示例:
- class C {
- x = 0;
- y = 0;
- }
- type T0 = InstanceType<typeof C>; // type T0 = C
- type T1 = InstanceType<any>; // type T1 = any
源碼定義:
- /**
- * Obtain the return type of a constructor function type
- */
- 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。
- function toHex(this: Number) {
- return this.toString(16);
- }
- function numberToString(n: ThisParameterType<typeof toHex>) { // 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> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
如果想了解如何在函數中定義this,建議還是看官網。
OmitThisParameter<Type>
作用:移除函數類型Type中參數的this。
示例:
- function toHex(this: Number) {
- return this.toString(16);
- }
- const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5); // const fiveToHex: () => string
- console.log(fiveToHex());
源碼定義:
- /**
- * Removes the 'this' parameter from a function type.
- */
- 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
- 參考官網。