TypeScript Utility Types All In One
TypeScript v4.8.4
Awaited<Type>
Partial<Type>
Required<Type>
Readonly<Type>
Record<Keys, Type>
Pick<Type, Keys>
Omit<Type, Keys>
Exclude<UnionType, ExcludedMembers>
Extract<Type, Union>
NonNullable<Type>
Parameters<Type>
ConstructorParameters<Type>
ReturnType<Type>
InstanceType<Type>
ThisParameterType<Type>
OmitThisParameter<Type>
ThisType<Type>
Intrinsic String Manipulation Types
Uppercase<StringType>
Lowercase<StringType>
Capitalize<StringType>
Uncapitalize<StringType>
https://www.typescriptlang.org/docs/handbook/utility-types.html
Awaited<Type>
This type is meant to model operations like await
in async functions
, or the .then()
method on Promises
- specifically, the way that they recursively unwrap Promises.
这种类型旨在模拟异步函数
中的 await
或 Promises
上的 .then()
方法等操作 - 特别是它们递归解包 Promises 的方式。
type A = Awaited<Promise<string>>;
// type A = string
type B = Awaited<Promise<Promise<number>>>;
// type B = number
type C = Awaited<boolean | Promise<number>>;
// type C = number | boolean
Partial<Type>
Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.
构造一个类型,其中 Type 的所有属性
都设置为可选
。此实用程序将返回一个表示给定类型的所有子集的类型。
interface Todo {
title: string;
description: string;
}
// type Test = Partial<number>;
// type Partial<T> = { [P in keyof T]?: T[P] | undefined; }
// 把一个类型的`所有属性`都变成`可选的`, 生成一个新类型 ✅
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
// (parameter) todo: Todo
// (parameter) fieldsToUpdate: Partial<Todo>
return {
...todo,
...fieldsToUpdate,
};
}
/*
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>): {
title: string;
description: string;
}
*/
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
/*
const todo1: {
title: string;
description: string;
}
*/
const todo2 = {
description: "throw out trash",
};
/*
const todo2: {
description: string;
}
*/
const todo = updateTodo(todo1, todo2);
/*
const todo: {
title: string;
description: string;
}
*/
Required<Type>
Constructs a type consisting of all properties of Type set to required. The opposite of Partial.
构造一个类型,该类型由设置为 required
的 Type 的所有属性
组成。与 Partial
正好相反。
interface Props {
a: number;
b?: string;
c?: string;
}
const obj1: Props = { a: 5 };
const obj2: Props = { a: 5, c: 'c' };
// 把一个类型的`所有属性`都变成`required`, 生成一个新类型 ✅
const obj3: Required<Props> = { a: 5, b: 'b', c: 'c' };
// type Required<T> = { [P in keyof T]-?: T[P]; }
// const obj3: Required<Props>
const obj4: Required<Props> = { a: 5 };
// ❌ Type '{ a: number; }' is missing the following properties from type 'Required<Props>': b, c(2739)
Readonly<Type>
Constructs a type with all properties of Type set to readonly
, meaning the properties of the constructed type cannot be reassigned.
构造一个 Type 的所有属性
都设置为 readonly
的类型,这意味着构造类型的属性不能被重新分配。
// @errors: 2540
interface Todo {
title: string;
}
// 把一个类型的`所有属性`都变成 `readonly`, 生成一个新类型 ✅
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
// readonly 不可重新赋值
todo.title = "Hello";
// const todo: Readonly<Todo>
// ❌ (property) title: any
// Cannot assign to 'title' because it is a read-only property.(2540)
This utility is useful for representing assignment expressions that will fail at runtime (i.e. when attempting to reassign properties of a frozen object).
此实用程序对于表示将在运行时失败(例如,尝试重新分配冻结对象的属性时)的赋值表达式很有用。
Object.freeze
function freeze<Type>(obj: Type): Readonly<Type>;
// function freeze<Type>(obj: Type): Readonly<Type>
// ❌ Function implementation is missing or not immediately following the declaration.(2391)
Record<Keys, Type>
Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.
构造一个对象类型,其属性键为 Keys,其属性值为 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;
// const cats: Record<CatName, CatInfo>
// (property) boris: CatInfo
cats.mordred;
// const cats: Record<CatName, CatInfo>
// (property) mordred: CatInfo
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type
Pick<Type, Keys>
Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
通过从 Type 中选择/挑选
一组属性 Keys(字符串文字或字符串文字的联合)来构造一个类型。
interface Todo {
title: string;
description: string;
completed: boolean;
}
// 从一个类型中`挑选出`一些`字段/属性`,生成一个有该类型的`字段/属性`子集组成的一个新类型 ✅
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
// const todo: TodoPreview
https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
Omit<Type, Keys>
Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).
通过从 Type 中选择所有属性然后删除 Keys(字符串文字或字符串文字的联合)来构造一个类型。
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
// `过滤掉`一些`字段/属性`构成一个新的`字段/属性`子集 ✅
type TodoPreview = Omit<Todo, "description">;
/*
// 等价于
type TodoPreview = {
title: string;
completed: boolean;
createdAt: number;
}
*/
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
todo;
// const todo: TodoPreview
// `过滤掉`一些`字段/属性`构成一个新的`字段/属性`子集
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
/*
// 等价于
type TodoInfo = {
description: string;
title: string;
}
*/
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
todoInfo;
// const todoInfo: TodoInfo
https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys
refs
TypeScript Advanced Types All In One
https://www.cnblogs.com/xgqfrms/p/15877490.html
https://github.com/xgqfrms/learn-typescript-by-practice/issues/21
https://github.com/xgqfrms/learn-typescript-by-practice/issues/22
https://github.com/xgqfrms/learn-typescript-by-practice/issues/23
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!