TypeScript utility types

Whilst looking into the NonNullable<> type I noticed there’s a bunch of utility types. These types are used to construct other types.

I’m having trouble at this time understanding the use cases for some of these types, so will solely cover those that I can see use cases for.

Starting point

Let’s create a simple interface which we’ll start off with

interface Person {
    name: string;
    age: number;
}

Partial<T>

Use case

We might have a type T with one or more mandatory fields, Partial<T> takes a type T and produces a new type where all fields are optional, so using

type PartialPerson = Partial<Person>;

will create

interface PartialPerson {
    name?: string;
    age?: number;
}

Required<T>

Use case

The opposite to Partial<T> we may have a type with one or more optional fields and we want to produce a type with mandatory fields, so using

interface PartialPerson {
    name?: string;
    age?: number;
}

type RequiredPerson = Required<PartialPerson>

will create

interface RequiredPerson {
    name: string;
    age: number;
}

Readonly<T>

Use case

In some cases we might have a type T and wish to generate a new type where all those fields are marked as readonly, so using

type ReadonlyPerson = Readonly<Person>;

will create

interface ReadonlyPerson {
    readonly name: string;
    readonly age: number;
}

Record<K, T>

Use case

We might wish to generate a new type with fields of type T.

The Record<K, T> takes two types and produces a new type per value passed into the type parameter K of type parameter T, so for example

type RecordPerson = Record<'mother' | 'father', Person>;

will create

interface RecordPerson {
    mother: Person;
    father: Person;
}

Pick<T, K>

Use case

We might have a type T and wish to generate a new type made up of just selected fields.

The Pick<T, K> takes a type T and keys, K, as a union from T. The new type will then be made up of the fields declared in K, for example

type PickPerson = Pick<Person, 'name'>

will create

interface PickPerson {
    name: string;
}

ReturnType<T>

Use case

Useful in situations where we have a function and we want to get the type being returned by the function.

The ReturnType takes a type function T and returns the return type from the function, so let’s create the following code

function getPerson() : Person {
    return { name: "Scooby", age: 12 }
}

type ReturnsPerson = ReturnType<typeof getPerson>;