- A+
TypeScript中的实用工具类型是一些预定义的泛型类型,可用于操作或创建其它新类型。这些实用工具类型在所有TypeScript项目中都是全局可用的,因此无需添加任务依赖项即可使用它们。
1.Partial<Type>
将Type的所有属性都设置为可选的类型。
1 interface Person { 2 name: string; 3 age: number; 4 email: string; 5 } 6 7 type PartialPerson = Partial<Person>; 8 9 //相当于 10 // interface Person { 11 // name?: string | undefined; 12 // age?: number | undefined; 13 // email?: string | undefined; 14 // } 15 16 interface Todo { 17 title: string; 18 description: string; 19 } 20 21 function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { 22 return { ...todo, ...fieldsToUpdate }; 23 } 24 25 const todo1 = { 26 title: "organize desk", 27 description: "clear clutter", 28 }; 29 30 const todo2 = updateTodo(todo1, { 31 description: "throw out trash", 32 });
2.Required<Type>
与Partical<Type> 相反,该类型由Type中所有属性设置为required组成。
1 interface Person { 2 name?: string | undefined; 3 age?: number | undefined; 4 email?: string | undefined; 5 } 6 7 8 type RequiredPerson = Required<Person>; 9 10 // 相当于 11 // interface Person { 12 // name: string; 13 // age: number; 14 // email: string; 15 // }
3.Omit<Type, Keys>
构建一个新类型--从类型 Type
中获取所有属性,然后从中剔除 Keys
属性。
1 interface User { 2 id: number; 3 name: string; 4 email: string; 5 age: number; 6 } 7 8 type UserWithoutEmail = Omit<User, 'email'>; 9 10 // 相当于 11 // interface Person { 12 // id: string; 13 // name: string; 14 // age: number; 15 // }
也可以移除多个属性,
1 interface User { 2 id: number; 3 name: string; 4 email: string; 5 age: number; 6 } 7 8 type UserWithoutEmailAndName = Omit<User, 'email' | 'name'>; 9 10 // 相当于 11 // interface Person { 12 // id: string; 13 // age: number; 14 // }
4.Pick<Type, Keys>
从类型 Type
中挑选部分属性 Keys
来构造类型,与Omit相反。
1 interface User { 2 id: number; 3 name: string; 4 email: string; 5 age: number; 6 } 7 8 type UserWithEmailAndName = Pick<User, 'email' | 'name'>; 9 10 // 相当于 11 // interface Person { 12 // name: string; 13 // email: string; 14 // }
可以组合使用这些类型,创造新的类型
1 interface User { 2 id: number; 3 name: string; 4 email: string; 5 age: number; 6 } 7 8 type PartialPick = Partial<Pick<User, 'email' | 'name'>>; 9 10 // 相当于 11 // interface Person { 12 // name?: string | undefined; 13 // email?: string | undefined; 14 // }
1 interface User { 2 id: number; 3 name: string; 4 email: string; 5 age: number; 6 } 7 8 type OmitPartialPick = Omit<Partial<Pick<User, 'email' | 'name'>>, 'email'>; 9 10 // 相当于 11 // interface Person { 12 // name?: string | undefined; 13 // }
5.Readonly<Type>
通过该Type构造新类型,并将它所有的属性设置为只读的,也就意味着构造出的类型的属性不能被再次赋值。
1 interface Person { 2 id: number; 3 name: string; 4 age: number; 5 } 6 7 type ReadonlyPerson = Readonly<Person>; 8 9 //相当于 10 // interface Person { 11 // readonly id: number; 12 // readonly name: string; 13 // readonly age: number; 14 // } 15 16 const person: ReadonlyPerson = { 17 id: 1, 18 name: 'John', 19 age: 25 20 }; 21 22 person.name = 'Mike'; // Error: Cannot assign to 'name' because it is a read-only property.
这个类型可用来表示在运行时会失败的赋值表达式(比如,当尝试给冻结对象的属性再次赋值时)
Object.freeze
1 function freeze<T>(obj: T): Readonly<T>;
6.Record<Keys, Type>
构造一个对象类型,其属性为Keys,属性值为Type;该实用工具类型可用于将一种类型的属性映射到另一种类型。
1 interface CatInfo { 2 age: number; 3 breed: string; 4 } 5 6 type CatName = "miffy" | "boris" | "mordred"; 7 8 const cats: Record<CatName, CatInfo> = { 9 miffy: { age: 10, breed: "Persian" }, 10 boris: { age: 5, breed: "Maine Coon" }, 11 mordred: { age: 16, breed: "British Shorthair" }, 12 }; 13 14 cats.boris; 15
7.Exclude<UnionType, ExcludedMembers>
通过从 UnionType 中排除所有可分配给 ExcludedMembers 的属性来构造一个类型;也就是删除 union 类型的成员来创建新类型。
1 type T0 = Exclude<"a" | "b" | "c", "a">; 2 type T0 = "b" | "c" 3 4 type T1 = Exclude<"a" | "b" | "c", "a" | "b">; 5 type T1 = "c" 6 7 type T2 = Exclude<string | number | (() => void), Function>; 8 type T2 = string | number
8.Extract<Type, Union>
通过从 Type 中提取可分配给 Union 的所有联合成员来构造一个类型,与 Exclude 相反。
1 type T0 = Extract<"a" | "b" | "c", "a" | "f">; 2 type T0 = "a" 3 4 type T1 = Extract<string | number | (() => void), Function>; 5 type T1 = () => void
9.NonNullable<Type>
通过从 Type 中排除 null 和 undefined 来构造一个类型。
1 type T0 = NonNullable<string | number | undefined>; 2 type T0 = string | number 3 4 type T1 = NonNullable<string[] | null | undefined>; 5 type T1 = string[]
10.ReturnType<Type>
由函数类型 Type
的返回值类型构建一个新类型。
1 function add(a: number, b: number): number { 2 return a + b; 3 } 4 5 type AddReturnType = ReturnType<typeof add>; 6 // type AddReturnType = number; 7 8 9 function addStr(a: string, b: string): string{ 10 return a + b; 11 } 12 13 type AddReturnType2 = ReturnType<typeof addStr>; 14 // type AddReturnType2 = string; 15 16 type T0 = ReturnType<() => string>; 17 type T0 = string 18 19 type T1 = ReturnType<(s: string) => void>; 20 type T1 = void 21 22 type T2 = ReturnType<<T>() => T>; 23 type T2 = unknown 24 25 type T3 = ReturnType<<T extends U, U extends number[]>() => T>; 26 type T3 = number[]
11.Parameters<Type>
由函数类型 Type
的参数类型来构建出一个元组类型。
1 function add(a: number, b: string, c:boolean): string { 2 return a + b; 3 } 4 5 type AddReturnType = Parameters<typeof add>; 6 // type AddReturnType = [a: number, b: string, c:boolean]; 7 8 type T0 = Parameters<() => string>; 9 type T0 = [] 10 11 type T1 = Parameters<(s: string) => void>; 12 type T1 = [s: string] 13 14 type T2 = Parameters<<T>(arg: T) => T>; 15 type T2 = [arg: unknown]
12.Awaited<Type>
这种类型旨在模拟异步函数中的 await 或 Promises 上的 .then() 方法等操作——具体来说,就是它们递归展开 Promises 的方式。
1 async function fetchData(): Promise<string> { 2 // fetch data from API and return a string 3 } 4 5 type ResolvedResult = Awaited<ReturnType<typeof fetchData>>; 6 // type ResolvedResult = string 7 8 type A = Awaited<Promise<string>>; 9 type A = string 10 11 type B = Awaited<Promise<Promise<number>>>; 12 type B = number 13 14 type C = Awaited<boolean | Promise<number>>; 15 type C = number | boolean
以上,是较常用的一些实用工具类型。
参考资料:
https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype
https://dev.to/arafat4693/typescript-utility-types-that-you-must-know-4m6k