Utility Types

Awaited<Type>

Released: 4.5

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

Try this code ↗

type A = Awaited<Promise<string>>;

type A = string

typeB = Awaited<Promise<Promise<number>>>;

type B = number

typeC = Awaited<boolean | Promise<number>>;

type C = number | boolean

Partial<Type>

Released:2.1

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

Try this code ↗

interface Todo {
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:2.8

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

Example

Try this code ↗

interface Props {
a?: number;
b?: string;
}

constobj: Props = { a:5 };

constobj2: Required<Props> = { a:5 };
Generated error
Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly<Type>

Released:2.1

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

Example

Try this code ↗

interface Todo {
title: string;
}

consttodo: Readonly<Todo> = {
title:"Delete inactive users",
};

todo.title = "Hello";
Generated error
Cannot assign to 'title' because it is a read-only property.

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>;

Record<Keys, Type>

Released:2.1

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

Try this code ↗

interface CatInfo {
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" },
};

cats.boris;

const cats: Record<CatName, CatInfo>

Pick<Type, Keys>

Released:2.1

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

Example

Try this code ↗

interface Todo {
title: string;
description: string;
completed: boolean;
}

typeTodoPreview = Pick<Todo, "title" | "completed">;

consttodo: TodoPreview = {
title:"Clean room",
completed:false,
};

todo;

const todo: TodoPreview

Omit<Type, Keys>

Released:3.5

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

Try this code ↗

interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}

typeTodoPreview = Omit<Todo, "description">;

consttodo: TodoPreview = {
title:"Clean room",
completed:false,
createdAt:1615544252770,
};

todo;

const todo: TodoPreview

typeTodoInfo = Omit<Todo, "completed" | "createdAt">;

consttodoInfo: TodoInfo = {
title:"Pick up kids",
description:"Kindergarten closes at 5pm",
};

todoInfo;

const todoInfo: TodoInfo

Exclude<UnionType, ExcludedMembers>

Released:2.8

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

Example

Try this code ↗

type T0 = Exclude<"a" | "b" | "c", "a">;

type T0 = "b" | "c"
typeT1 = Exclude<"a" | "b" | "c", "a" | "b">;

type T1 = "c"
typeT2 = Exclude<string | number | (() =>void), Function>;

type T2 = string | number

typeShape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };

typeT3 = Exclude<Shape, { kind: "circle" }>

type T3 = {
    kind: "square";
    x: number;
} | {
    kind: "triangle";
    x: number;
    y: number;
}

Extract<Type, Union>

Released:2.8

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

Example

Try this code ↗

type T0 = Extract<"a" | "b" | "c", "a" | "f">;

type T0 = "a"
typeT1 = Extract<string | number | (() =>void), Function>;

type T1 = () => void

typeShape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };

typeT2 = Extract<Shape, { kind: "circle" }>

type T2 = {
    kind: "circle";
    radius: number;
}

NonNullable<Type>

Released:2.8

Constructs a type by excluding null and undefined from Type.

Example

Try this code ↗

type T0 = NonNullable<string | number | undefined>;

type T0 = string | number
typeT1 = NonNullable<string[] | null | undefined>;

type T1 = string[]

Parameters<Type>

Released:3.1 ↗

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

Try this code ↗

declare function f1(arg: { a: number; b: string }): void;

typeT0 = Parameters<() =>string>;

type T0 = []
typeT1 = Parameters<(s: string) =>void>;

type T1 = [s: string]
typeT2 = Parameters<<T>(arg: T) =>T>;

type T2 = [arg: unknown]
typeT3 = Parameters<typeoff1>;

type T3 = [arg: {
    a: number;
    b: string;
}]
typeT4 = Parameters<any>;

type T4 = unknown[]
typeT5 = Parameters<never>;

type T5 = never
typeT6 = Parameters<string>;

type T6 = never
typeT7 = 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
Generated error
Type 'string' does not satisfy the constraint '(...args: any) => any'.

ConstructorParameters<Type>

Released:3.1 ↗

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

Try this code ↗

type T0 = ConstructorParameters<ErrorConstructor>;

type T0 = [message?: string]
typeT1 = ConstructorParameters<FunctionConstructor>;

type T1 = string[]
typeT2 = ConstructorParameters<RegExpConstructor>;

type T2 = [pattern: string | RegExp, flags?: string]
classC {
constructor(a: number, b: string) {}
}
typeT3 = ConstructorParameters<typeofC>;

type T3 = [a: number, b: string]
typeT4 = ConstructorParameters<any>;

type T4 = unknown[]

typeT5 = ConstructorParameters<Function>;

type T5 = never
Generated error
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
  Type 'Function' provides no match for the signature 'new (...args: any): any'.

ReturnType<Type>

Released:2.8

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

Try this code ↗

declare function f1(): { a: number; b: string };

typeT0 = ReturnType<() =>string>;

type T0 = string
typeT1 = ReturnType<(s: string) =>void>;

type T1 = void
typeT2 = ReturnType<<T>() =>T>;

type T2 = unknown
typeT3 = ReturnType<<TextendsU, Uextendsnumber[]>() =>T>;

type T3 = number[]
typeT4 = ReturnType<typeoff1>;

type T4 = {
    a: number;
    b: string;
}
typeT5 = ReturnType<any>;

type T5 = any
typeT6 = ReturnType<never>;

type T6 = never
typeT7 = ReturnType<string>;

type T7 = any
typeT8 = 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
Generated error
Type 'string' does not satisfy the constraint '(...args: any) => any'.

InstanceType<Type>

Released:2.8

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

Example

Try this code ↗

class C {
x = 0;
y = 0;
}

typeT0 = InstanceType<typeofC>;

type T0 = C
typeT1 = InstanceType<any>;

type T1 = any
typeT2 = InstanceType<never>;

type T2 = never
typeT3 = InstanceType<string>;

type T3 = any
typeT4 = 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
Generated error
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.

ThisParameterType<Type>

Released:3.3 ↗

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

Example

Try this code ↗

function toHex(this: Number) {
returnthis.toString(16);
}

functionnumberToString(n: ThisParameterType<typeoftoHex>) {
returntoHex.apply(n);
}

OmitThisParameter<Type>

Released:3.3 ↗

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

Try this code ↗

function toHex(this: Number) {
returnthis.toString(16);
}

constfiveToHex: OmitThisParameter<typeoftoHex> = toHex.bind(5);

console.log(fiveToHex());

ThisType<Type>

Released:2.3 ↗

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

Try this code ↗

type ObjectDescriptor<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 this
this.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): 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>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

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.

Last updated on