TypeScript 提供了几种实用类型来简化常见的类型转换。这些实用工具在全局可用。
🌐 TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
Awaited<Type>
发布: 4.5
🌐 Released: 4.5
这种类型用于模拟像 async 函数中的 await 操作,或 Promise 上的 .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
tsTrytypeA =Awaited <Promise <string>>;typeB =Awaited <Promise <Promise <number>>>;typeC =Awaited <boolean |Promise <number>>;
Partial<Type>
发布: 2.1
🌐 Released:
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
tsTryinterfaceTodo {title : string;description : string;}functionupdateTodo (todo :Todo ,fieldsToUpdate :Partial <Todo >) {return { ...todo , ...fieldsToUpdate };}consttodo1 = {title : "organize desk",description : "clear clutter",};consttodo2 =updateTodo (todo1 , {description : "throw out trash",});
Required<Type>
发布: 2.8
🌐 Released:
2.8
构造一个类型,该类型包含 Type 的所有属性,并将它们设置为必填。这与 Partial 相反。
🌐 Constructs a type consisting of all properties of Type set to required. The opposite of Partial.
示例
🌐 Example
tsTryinterfaceProps {a ?: number;b ?: string;}constobj :Props = {a : 5 };constProperty '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>'.: obj2 Required <Props > = {a : 5 };
Readonly<Type>
发布: 2.1
🌐 Released:
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
tsTryinterfaceTodo {title : string;}consttodo :Readonly <Todo > = {title : "Delete inactive users",};Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.todo .= "Hello"; title
此工具对于表示在运行时会失败的赋值表达式非常有用(即尝试重新分配frozen 对象的属性时)。
🌐 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
tsfunction freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys, Type>
发布: 2.1
🌐 Released:
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
tsTrytypeCatName = "miffy" | "boris" | "mordred";interfaceCatInfo {age : number;breed : string;}constcats :Record <CatName ,CatInfo > = {miffy : {age : 10,breed : "Persian" },boris : {age : 5,breed : "Maine Coon" },mordred : {age : 16,breed : "British Shorthair" },};cats .boris ;
Pick<Type, Keys>
发布: 2.1
🌐 Released:
2.1
通过从 Type 中选择属性集 Keys(字符串字面量或字符串字面量的联合)来构造一个类型。
🌐 Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
示例
🌐 Example
tsTryinterfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Pick <Todo , "title" | "completed">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Omit<Type, Keys>
发布: 3.5
🌐 Released:
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
tsTryinterfaceTodo {title : string;description : string;completed : boolean;createdAt : number;}typeTodoPreview =Omit <Todo , "description">;consttodo :TodoPreview = {title : "Clean room",completed : false,createdAt : 1615544252770,};todo ;typeTodoInfo =Omit <Todo , "completed" | "createdAt">;consttodoInfo :TodoInfo = {title : "Pick up kids",description : "Kindergarten closes at 5pm",};todoInfo ;
Exclude<UnionType, ExcludedMembers>
发布: 2.8
🌐 Released:
2.8
通过从 UnionType 中排除所有可分配给 ExcludedMembers 的联合成员来构造一个类型。
🌐 Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
示例
🌐 Example
tsTrytypeT0 =Exclude <"a" | "b" | "c", "a">;typeT1 =Exclude <"a" | "b" | "c", "a" | "b">;typeT2 =Exclude <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT3 =Exclude <Shape , {kind : "circle" }>
Extract<Type, Union>
发布: 2.8
🌐 Released:
2.8
通过从 Type 中提取所有可分配给 Union 的联合成员来构造一个类型。
🌐 Constructs a type by extracting from Type all union members that are assignable to Union.
示例
🌐 Example
tsTrytypeT0 =Extract <"a" | "b" | "c", "a" | "f">;typeT1 =Extract <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT2 =Extract <Shape , {kind : "circle" }>
NonNullable<Type>
发布: 2.8
🌐 Released:
2.8
通过从 Type 中排除 null 和 undefined 来构造一个类型。
🌐 Constructs a type by excluding null and undefined from Type.
示例
🌐 Example
tsTrytypeT0 =NonNullable <string | number | undefined>;typeT1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
发布: 3.1
🌐 Released:
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
tsTrydeclare functionf1 (arg : {a : number;b : string }): void;typeT0 =Parameters <() => string>;typeT1 =Parameters <(s : string) => void>;typeT2 =Parameters <<T >(arg :T ) =>T >;typeT3 =Parameters <typeoff1 >;typeT4 =Parameters <any>;typeT5 =Parameters <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T6 =Parameters <string >;typeType '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'.T7 =Parameters <>; Function
ConstructorParameters<Type>
发布: 3.1
🌐 Released:
3.1
从构造函数类型的类型构造一个元组或数组类型。它会生成一个包含所有参数类型的元组类型(如果不是函数,则类型为 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
tsTrytypeT0 =ConstructorParameters <ErrorConstructor >;typeT1 =ConstructorParameters <FunctionConstructor >;typeT2 =ConstructorParameters <RegExpConstructor >;classC {constructor(a : number,b : string) {}}typeT3 =ConstructorParameters <typeofC >;typeT4 =ConstructorParameters <any>;typeType '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'.T5 =ConstructorParameters <>; Function
ReturnType<Type>
发布: 2.8
🌐 Released:
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
tsTrydeclare functionf1 (): {a : number;b : string };typeT0 =ReturnType <() => string>;typeT1 =ReturnType <(s : string) => void>;typeT2 =ReturnType <<T >() =>T >;typeT3 =ReturnType <<T extendsU ,U extends number[]>() =>T >;typeT4 =ReturnType <typeoff1 >;typeT5 =ReturnType <any>;typeT6 =ReturnType <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T7 =ReturnType <string >;typeType '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'.T8 =ReturnType <>; Function
InstanceType<Type>
发布: 2.8
🌐 Released:
2.8
构造一个类型,该类型由 Type 中构造函数的实例类型组成。
🌐 Constructs a type consisting of the instance type of a constructor function in Type.
示例
🌐 Example
tsTryclassC {x = 0;y = 0;}typeT0 =InstanceType <typeofC >;typeT1 =InstanceType <any>;typeT2 =InstanceType <never>;typeType 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.T3 =InstanceType <string >;typeType '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'.T4 =InstanceType <>; Function
NoInfer<Type>
发布: 5.4
🌐 Released:
5.4
阻止对包含类型的推断。除了阻止推断之外,NoInfer<Type> 与 Type 完全相同。
🌐 Blocks inferences to the contained type. Other than blocking inferences, NoInfer<Type> is
identical to Type.
示例
🌐 Example
tsfunction createStreetLight<C extends string>(colors: C[],defaultColor?: NoInfer<C>,) {// ...}createStreetLight(["red", "yellow", "green"], "red"); // OKcreateStreetLight(["red", "yellow", "green"], "blue"); // Error
ThisParameterType<Type>
发布: 3.3
🌐 Released:
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
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
发布: 3.3
🌐 Released:
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
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);console .log (fiveToHex ());
ThisType<Type>
发布: 2.3
🌐 Released:
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
tsTrytypeObjectDescriptor <D ,M > = {data ?:D ;methods ?:M &ThisType <D &M >; // Type of 'this' in methods is D & M};functionmakeObject <D ,M >(desc :ObjectDescriptor <D ,M >):D &M {letdata : object =desc .data || {};letmethods : object =desc .methods || {};return { ...data , ...methods } asD &M ;}letobj =makeObject ({data : {x : 0,y : 0 },methods : {moveBy (dx : number,dy : number) {this.x +=dx ; // Strongly typed thisthis.y +=dy ; // Strongly typed this},},});obj .x = 10;obj .y = 20;obj .moveBy (5, 5);
在上面的例子中,传递给 makeObject 的参数中的 methods 对象具有包含 ThisType<D & M> 的上下文类型,因此在 methods 对象的方法中 [this](/docs/handbook/functions.html#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.