- Utility Types
Partial<Type>
Required<Type>
Readonly<Type>
Record<Keys,Type>
Pick<Type, Keys>
Omit<Type, Keys>
Exclude<Type, ExcludedUnion>
Extract<Type, Union>
NonNullable<Type>
Parameters<Type>
ConstructorParameters<Type>
ReturnType<Type>
InstanceType<Type>
ThisParameterType<Type>
OmitThisParameter<Type>
ThisType<Type>
- Intrinsic String Manipulation Types
Utility Types
TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
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.
Example
interfaceTodo {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>
Constructs a type consisting of all properties of Type
set to required. The opposite of Partial
.
Example
interfaceProps {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>
Constructs a type with all properties of Type
set to readonly
, meaning the properties of the constructed type cannot be reassigned.
Example
interfaceTodo {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
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>
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
interfaceCatInfo {age : number;breed : string;}
typeCatName = "miffy" | "boris" | "mordred";
constcats :Record <CatName ,CatInfo > = {miffy : {age : 10,breed : "Persian" },boris : {age : 5,breed : "Maine Coon" },mordred : {age : 16,breed : "British Shorthair" }};
// ^ = const cats: Recordcats .boris ;
Pick<Type, Keys>
Constructs a type by picking the set of properties Keys
from Type
.
Example
interfaceTodo {title : string;description : string;completed : boolean;}
typeTodoPreview =Pick <Todo , "title" | "completed">;
consttodo :TodoPreview = {title : "Clean room",completed : false,};
// ^ = const todo: TodoPreviewtodo ;
Omit<Type, Keys>
Constructs a type by picking all properties from Type
and then removing Keys
.
Example
interfaceTodo {title : string;description : string;completed : boolean;}
typeTodoPreview =Omit <Todo , "description">;
consttodo :TodoPreview = {title : "Clean room",completed : false,};
// ^ = const todo: TodoPreviewtodo ;
Exclude<Type, ExcludedUnion>
Constructs a type by excluding from Type
all union members that are assignable to ExcludedUnion
.
Example
type// ^ = type T0 = "b" | "c"T0 =Exclude <"a" | "b" | "c", "a">;
type// ^ = type T1 = "c"T1 =Exclude <"a" | "b" | "c", "a" | "b">;
type// ^ = type T2 = string | numberT2 =Exclude <string | number | (() => void),Function >;
Extract<Type, Union>
Constructs a type by extracting from Type
all union members that are assignable to Union
.
Example
type// ^ = type T0 = "a"T0 =Extract <"a" | "b" | "c", "a" | "f">;
type// ^ = type T1 = () => voidT1 =Extract <string | number | (() => void),Function >;
NonNullable<Type>
Constructs a type by excluding null
and undefined
from Type
.
Example
type// ^ = type T0 = string | numberT0 =NonNullable <string | number | undefined>;
type// ^ = type T1 = string[]T1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
Constructs a tuple type from the types used in the parameters of a function type Type
.
Example
declare functionf1 (arg : {a : number;b : string }): void;
type// ^ = type T0 = []T0 =Parameters <() => string>;
type// ^ = type T1 = [s: string]T1 =Parameters <(s : string) => void>;
type// ^ = type T2 = [arg: unknown]T2 =Parameters <<T >(arg :T ) =>T >;
type// ^ = type T3 = [arg: {T3 =Parameters <typeoff1 >;// a: number;
// b: string;
// }]
type// ^ = type T4 = unknown[]T4 =Parameters <any>;
type// ^ = type T5 = neverT5 =Parameters <never>;
typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.// ^ = type T6 = neverT6 =Parameters <string>;
typeType 'Function' does not satisfy the constraint '(...args: any) => any'.T7 =Parameters <Function >;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
ConstructorParameters<Type>
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
type// ^ = type T0 = [message?: string]T0 =ConstructorParameters <ErrorConstructor >;
type// ^ = type T1 = string[]T1 =ConstructorParameters <FunctionConstructor >;
type// ^ = type T2 = [pattern: string | RegExp, flags?: string]T2 =ConstructorParameters <RegExpConstructor >;
type// ^ = type T3 = unknown[]T3 =ConstructorParameters <any>;
typeType 'Function' does not satisfy the constraint 'new (...args: any) => any'.T4 =ConstructorParameters <Function >;Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'.// ^ = type T4 = never
ReturnType<Type>
Constructs a type consisting of the return type of function Type
.
Example
declare functionf1 (): {a : number;b : string };
type// ^ = type T0 = stringT0 =ReturnType <() => string>;
type// ^ = type T1 = voidT1 =ReturnType <(s : string) => void>;
type// ^ = type T2 = unknownT2 =ReturnType <<T >() =>T >;
type// ^ = type T3 = number[]T3 =ReturnType <<T extendsU ,U extends number[]>() =>T >;
type// ^ = type T4 = {T4 =ReturnType <typeoff1 >;// a: number;
// b: string;
// }
type// ^ = type T5 = anyT5 =ReturnType <any>;
type// ^ = type T6 = neverT6 =ReturnType <never>;
typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.// ^ = type T7 = anyT7 =ReturnType <string>;
typeType 'Function' does not satisfy the constraint '(...args: any) => any'.T8 =ReturnType <Function >;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
InstanceType<Type>
Constructs a type consisting of the instance type of a constructor function in Type
.
Example
classC {x = 0;y = 0;}
type// ^ = type T0 = CT0 =InstanceType <typeofC >;
type// ^ = type T1 = anyT1 =InstanceType <any>;
type// ^ = type T2 = neverT2 =InstanceType <never>;
typeType 'string' does not satisfy the constraint 'new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'new (...args: any) => any'.// ^ = type T3 = anyT3 =InstanceType <string>;
typeType 'Function' does not satisfy the constraint 'new (...args: any) => any'.T4 =InstanceType <Function >;Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'.// ^ = type T4 = any
ThisParameterType<Type>
Extracts the type of the this parameter for a function type, or unknown if the function type has no this
parameter.
Example
functiontoHex (this :Number ) {return this.toString (16);}
functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
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
functiontoHex (this :Number ) {return this.toString (16);}
constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);
console .log (fiveToHex ());
ThisType<Type>
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
typeObjectDescriptor <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);
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): number }
. Notice how the type of the methods
property simultaneously is an inference target and a source for the this
type in methods.
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
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.