工具类型

TypeScript 提供了几种工具类型来促进常见的类型转换。这些工具在全局作用域内可用。

¥TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.

Awaited<Type>

发布于:4.5

此类型旨在对 async 函数中的 awaitPromise 中的 .then() 方法等操作进行建模 - 具体来说,他们递归地解开 Promise 的方式。

¥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.

示例

¥Example

ts
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
Try

Partial<Type>

发布于:2.1

构造一个将 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.

示例

¥Example

ts
interface Todo {
title: string;
description: string;
}
 
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",
});
Try

Required<Type>

发布于:2.8

构造一个由设置为 required 的 Type 的所有属性组成的类型。与 Partial 相反。

¥Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

示例

¥Example

ts
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>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
Try

Readonly<Type>

发布于:2.1

构造一个将 Type 的所有属性设置为 readonly 的类型,这意味着构造类型的属性不能重新分配。

¥Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.

示例

¥Example

ts
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.2540Cannot assign to 'title' because it is a read-only property.
Try

此工具对于表示将在运行时失败的赋值表达式很有用(即尝试重新分配 冻结对象 的属性时)。

¥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
ts
function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys, Type>

发布于:2.1

构造一个对象类型,其属性键为 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.

示例

¥Example

ts
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>
Try

Pick<Type, Keys>

发布于:2.1

通过从 Type 中选取一组属性 Keys(字符串字面或字符串字面的并集)来构造一个类型。

¥Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.

示例

¥Example

ts
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
Try

Omit<Type, Keys>

发布于:3.5

通过从 Type 中选择所有属性然后删除 Keys(字符串字面或字符串字面的并集)来构造一个类型。与 Pick 相反。

¥Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals). The opposite of Pick.

示例

¥Example

ts
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
 
todo;
const todo: TodoPreview
 
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
 
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
 
todoInfo;
const todoInfo: TodoInfo
Try

Exclude<UnionType, ExcludedMembers>

发布于:2.8

通过从 UnionType 中排除所有可分配给 ExcludedMembers 的联合成员来构造一个类型。

¥Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.

示例

¥Example

ts
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
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T3 = Exclude<Shape, { kind: "circle" }>
type T3 = { kind: "square"; x: number; } | { kind: "triangle"; x: number; y: number; }
Try

Extract<Type, Union>

发布于:2.8

通过从 Type 中提取所有可分配给 Union 的联合成员来构造一个类型。

¥Constructs a type by extracting from Type all union members that are assignable to Union.

示例

¥Example

ts
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
type T1 = () => void
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T2 = Extract<Shape, { kind: "circle" }>
type T2 = { kind: "circle"; radius: number; }
Try

NonNullable<Type>

发布于:2.8

通过从 Type 中排除 nullundefined 来构造一个类型。

¥Constructs a type by excluding null and undefined from Type.

示例

¥Example

ts
type T0 = NonNullable<string | number | undefined>;
type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
type T1 = string[]
Try

Parameters<Type>

发布于:3.1

从函数类型 Type 的参数中使用的类型构造元组类型。

¥Constructs a tuple type from the types used in the parameters of a function type Type.

对于重载函数,这将是最后一个签名的参数;见 在条件类型中推断

¥For overloaded functions, this will be the parameters of the last signature; see Inferring Within Conditional Types.

示例

¥Example

ts
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'.2344Type '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'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
type T7 = never
Try

ConstructorParameters<Type>

发布于:3.1

从构造函数类型的类型构造元组或数组类型。它生成一个包含所有参数类型的元组类型(如果 Type 不是函数,则生成类型 never)。

¥Constructs a tuple or array type from the types of a constructor function type. It produces a tuple type with all the parameter types (or the type never if Type is not a function).

示例

¥Example

ts
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]
class C {
constructor(a: number, b: string) {}
}
type T3 = ConstructorParameters<typeof C>;
type T3 = [a: number, b: string]
type T4 = ConstructorParameters<any>;
type T4 = unknown[]
 
type T5 = ConstructorParameters<Function>;
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
type T5 = never
Try

ReturnType<Type>

发布于:2.8

构造一个由函数 Type 的返回类型组成的类型。

¥Constructs a type consisting of the return type of function Type.

对于重载函数,这将是最后一个签名的返回类型;见 在条件类型中推断

¥For overloaded functions, this will be the return type of the last signature; see Inferring Within Conditional Types.

示例

¥Example

ts
declare function f1(): { a: number; b: string };
 
type T0 = ReturnType<() => string>;
type T0 = string
type T1 = ReturnType<(s: string) => void>;
type T1 = void
type T2 = ReturnType<<T>() => T>;
type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T3 = number[]
type T4 = ReturnType<typeof f1>;
type T4 = { a: number; b: string; }
type T5 = ReturnType<any>;
type T5 = any
type T6 = ReturnType<never>;
type T6 = never
type T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type T8 = ReturnType<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
type T8 = any
Try

InstanceType<Type>

发布于:2.8

构造一个由 Type 中的构造函数的实例类型组成的类型。

¥Constructs a type consisting of the instance type of a constructor function in Type.

示例

¥Example

ts
class C {
x = 0;
y = 0;
}
 
type T0 = InstanceType<typeof C>;
type T0 = C
type T1 = InstanceType<any>;
type T1 = any
type T2 = InstanceType<never>;
type T2 = never
type T3 = InstanceType<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<Function>;
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
type T4 = any
Try

ThisParameterType<Type>

发布于:3.3

提取函数类型的 this 参数的类型,如果函数类型没有 this 参数,则提取 unknown

¥Extracts the type of the this parameter for a function type, or unknown if the function type has no this parameter.

示例

¥Example

ts
function toHex(this: Number) {
return this.toString(16);
}
 
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
Try

OmitThisParameter<Type>

发布于:3.3

Type 中删除 this 参数。如果 Type 没有显式声明的 this 参数,则结果只是 Type。否则,将从 Type 创建一个没有 this 参数的新函数类型。泛型被删除,只有最后一个重载签名被传播到新的函数类型中。

¥Removes the this parameter from Type. If Type has no explicitly declared this parameter, the result is simply Type. Otherwise, a new function type with no this parameter is created from Type. Generics are erased and only the last overload signature is propagated into the new function type.

示例

¥Example

ts
function toHex(this: Number) {
return this.toString(16);
}
 
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
 
console.log(fiveToHex());
Try

ThisType<Type>

发布于:2.3

此工具不返回转换后的类型。相反,它用作上下文 this 类型的标记。请注意,必须启用 noImplicitThis 标志才能使用此工具。

¥This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the noImplicitThis flag must be enabled to use this utility.

示例

¥Example

ts
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};
 
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
let data: object = desc.data || {};
let methods: object = desc.methods || {};
return { ...data, ...methods } as D & M;
}
 
let obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // Strongly typed this
this.y += dy; // Strongly typed this
},
},
});
 
obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);
Try

在上面的示例中,makeObject 参数中的 methods 对象具有包含 ThisType<D & M> 的上下文类型,因此 methods 对象内的方法中的 this 类型是 { x: number, y: number } & { moveBy(dx: number, dy: number): void }。请注意 methods 属性的类型如何同时是方法中 this 类型的推断目标和源。

¥In the example above, the methods object in the argument to makeObject has a contextual type that includes ThisType<D & M> and therefore the type of this in methods within the methods object is { x: number, y: number } & { moveBy(dx: number, dy: number): void }. Notice how the type of the methods property simultaneously is an inference target and a source for the this type in methods.

ThisType<T> 标记接口只是在 lib.d.ts 中声明的一个空接口。除了在对象字面的上下文类型中被识别之外,接口的行为就像任何空接口。

¥The ThisType<T> marker interface is simply an empty interface declared in lib.d.ts. Beyond being recognized in the contextual type of an object literal, the interface acts like any empty interface.

内在字符串操作类型

¥Intrinsic String Manipulation Types

Uppercase<StringType>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

为了帮助围绕模板字符串字面进行字符串操作,TypeScript 包含一组可用于类型系统内的字符串操作的类型。你可以在 模板字面类型 文档中找到这些内容。

¥To help with string manipulation around template string literals, TypeScript includes a set of types which can be used in string manipulation within the type system. You can find those in the Template Literal Types documentation.