TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
Awaited<Type>
Released:
This type is meant to model operations like
await
in
async
functions, or the
.then()
method on
Promise
s - specifically, the way that they recursively
unwrap
Promise
s.
Example
ts
typeA =Awaited <Promise <string>>;
Partial<Type>
Released:
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
tsTry
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>
Released:
Constructs a type consisting of all properties of
Type
set to required. The opposite of
Partial
.
Example
tsTry
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>
Released:
Constructs a type with all properties of
Type
set to
readonly
, meaning the properties of the constructed type cannot be reassigned.
Example
tsTry
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>
Released:
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
typeCatName = "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>
Released:
Constructs a type by picking the set of properties
Keys
(string literal or union of string literals) from
Type
.
Example
ts
interfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Pick <Todo , "title" | "completed">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Omit<Type, Keys>
Released:
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
interfaceTodo {title : string;description : string;completed : boolean;createdAt : number;}typeTodoPreview =Omit <Todo , "description">;consttodo :TodoPreview = {title : "Clean room",completed : false,createdAt : 1615544252770,};todo ;
Exclude<UnionType, ExcludedMembers>
Released:
Constructs a type by excluding from
UnionType
all union members that are assignable to
ExcludedMembers
.
Example
ts
typeT0 =Exclude <"a" | "b" | "c", "a">;
Extract<Type, Union>
Released:
Constructs a type by extracting from
Type
all union members that are assignable to
Union
.
Example
ts
typeT0 =Extract <"a" | "b" | "c", "a" | "f">;
NonNullable<Type>
Released:
Constructs a type by excluding
null
and
undefined
from
Type
.
Example
ts
typeT0 =NonNullable <string | number | undefined>;
Parameters<Type>
Released:
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 functionf1 (arg : {a : number;b : string }): void;typeT0 =Parameters <() => string>;
ConstructorParameters<Type>
Released:
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
tstype T0 = ConstructorParameters <ErrorConstructor >;
ReturnType<Type>
Released:
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
tsdeclare function f1 (): { a : number; b : string }; type T0 = ReturnType <() => string>;
InstanceType<Type>
Released:
Constructs a type consisting of the instance type of a constructor function in
Type
.
Example
tsclass C { x = 0; y = 0;} type T0 = InstanceType <typeof C >;
NoInfer<Type>
Released:
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>
Released:
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>
Released:
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
tsfunction toHex (this : Number ) { return this.toString (16);} const fiveToHex : OmitThisParameter <typeof toHex > = toHex .bind (5); console .log (fiveToHex ());
Try
ThisType<Type>
Released:
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
tstype 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
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.
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>