TypeScript

TypeScript Utility Types Explained

Partial, Required, Readonly, Pick, Omit, Record, NonNullable, Extract, Exclude Types

Jeroen Ouwehand
ITNEXT
Published in
3 min readMay 17, 2021

--

Photo by Ash Edmonds on Unsplash

In TypeScript, there are multiple built-in utility (default) types. It would be a good thing to know they exist because they are handy in some situations. Some are easier to understand than others. I am going to explain them in a short and simple way, so everyone can understand them.

1 — Partial

The first one is Partial, this can make all properties optional in a type where properties originally should be required.

type Worker = {
name: string;
profession: string;
}
// Not defining 'profession' is allowed
const worker: Partial<Worker> = {
name: 'Jeroen'
}

2 — Required

The opposite one of Partial is Required, instead of making properties optional, it makes them required.

type Worker = {
name?: string;
profession?: string;
}
// You should defining 'name' and 'profession'
const worker: Required<Worker> = {
name: 'Jeroen',
profession: 'Developer',
}

3 — Readonly

With Readonly, you prevent that properties are going to be re-assigned.

type Worker = {
name: string;
profession: string;
}
const worker: Readonly<Worker> = {
name: 'Jeroen',
profession: 'Developer',
}
worker.name = 'Bob'; // Not allowed

4 — Pick

A more advanced utility type is Pick, which can be used to include only a few properties.

type Worker = {
name: string;
profession: string;
isWorking: boolean;
}
// Only 'name' and 'isWorking' are included
const worker: Pick<Worker, 'name' | 'isWorking'> = {
name: 'Jeroen',
isWorking: true,
}

5 — Omit

The opposite way of the Pick type is called Omit, you exclude the properties you don’t want to use.

type Worker = {
name: string;
profession: string;
isWorking: boolean;
}

--

--