Utility Types — TypeScript

Utility types are built-in types that make new types from existing ones. The examples use the interface User (id, name, email required, age optional)…

There's a User with id, name and email. The sign-up form needs a version without id, the profile card only needs name and email, and update data (data that changes a user) may hold just some of the fields. Writing three new interfaces that are almost the same is tiring. And as soon as User changes, all three are out of date.

A utility type makes those versions directly from User. It's a built-in TypeScript type that makes a new type from a type you already have: Partial<User>, Pick<User, ...> or Omit<User, ...>. Think of photocopying: from one original document you can make a copy where every field may stay empty, a copy with only two fields, or a copy without a certain field. The original doesn't change. Here the original document is User, each field is one property, and each copy is a new type made by a utility type.

Every example below uses this interface:

interface User {
  id: number;
  name: string;
  email: string;
  age?: number; // optional
}

A utility type is written with angle brackets < >, just like a generic, because it is a generic: User fills its type parameter.

Partial and Required

Partial<T> makes every property optional. Required<T> is the opposite: every property becomes required, including the ones that had a ?. Here is Partial<User> next to a plain User:

// Partial<User> is the same as { id?: number; name?: string; email?: string; age?: number }
const empty: Partial<User> = {}; // passes
const wrong: User = {};          // error
error TS2739: Type '{}' is missing the following properties from type 'User': id, name, email

{} passes as a Partial<User>, but is refused as a User, because id, name and email are required. Partial fits update data that only changes some fields, like { email: "[email protected]" }.

Required<User> makes age required too, so an object without age is refused:

// Required<User> is the same as { id: number; name: string; email: string; age: number }
const complete: Required<User> = { id: 1, name: "Budi", email: "[email protected]" }; // error
error TS2741: Property 'age' is missing in type '{ id: number; name: string; email: string; }' but required in type 'Required<User>'.

Pick and Omit

Pick<T, K> keeps only certain properties. Omit<T, K> is the opposite: it drops certain properties and keeps the rest. K is a union of property names, like what keyof gives you.

type ProfileCard = Pick<User, "name" | "email">;
// the same as { name: string; email: string }

type SignUpForm = Omit<User, "id">;
// the same as { name: string; email: string; age?: number }

const form: SignUpForm = { id: 1, name: "Budi", email: "[email protected]" }; // error

The last line is rejected:

error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Omit<User, "id">'.

Readonly and Record

Readonly<T> makes every property unchangeable once the object is made:

const admin: Readonly<User> = { id: 1, name: "Budi", email: "[email protected]" };
admin.name = "Ani"; // error
error TS2540: Cannot assign to 'name' because it is a read-only property.

Record<K, V> is the type of an object whose keys are of type K and whose values are of type V:

type Name = "budi" | "ani" | "rina";
const scores: Record<Name, number> = { budi: 7, ani: 7, rina: 7 }; // all three names required

const points: Record<string, number> = {}; // any string key, number values
points["budi"] = 0;
points["ani"] = 0; // points is now { budi: 0, ani: 0 }

There are other utility types you will often meet. Say there is function makeUser(name: string): User and async function getUser(id: number): Promise<User>:

Utility type What it gives
ReturnType<typeof makeUser> the function's return type: User
Parameters<typeof makeUser> a tuple of its parameters: [name: string]
Awaited<ReturnType<typeof getUser>> what the Promise holds (what you get with await): User
NonNullable<string | null | undefined> string, without null and undefined
Exclude<"small" | "medium" | "large", "small"> removes union members: "medium" | "large". Its opposite, Extract, keeps only the ones that match.

typeof makeUser, written where a type goes, takes the type from a function that already exists. So the type changes when the function changes.

⚠️ A Partial that's too loose, and an Omit that stays quiet

TL;DR: Utility types are built-in types that make new types from existing ones. The examples use the interface User (id, name, email required, age optional). Partial<User> makes every property optional (so {} passes), Required<User> makes them all required, and Readonly<User> makes them unchangeable. Pick<User, "name" | "email"> keeps only the properties you name. Omit<User, "id"> is the opposite: it drops the properties you name. Record<K, V> is an object with keys (property names) of type K and values of type V, like Record<string, number> for a score per name such as { budi: 0, ani: 0 }.

⚡ Partial: everything becomes optional

Write:

const empty: Partial<User> = {}; // passes
const wrong: User = {};          // error

Meaning: User here is an interface with the required id, name and email, and the optional age?. A utility type such as Partial is a built-in type that makes a new type from User without changing the original. Partial<User> makes every property optional, so {} is accepted. This suits update data (data that changes only some of a user's fields). Required<User> is the opposite: everything is required, age? included.

⚡ Pick takes, Omit drops

Write:

type ProfileCard = Pick<User, "name" | "email">;
type SignUpForm = Omit<User, "id">;
Guess first: Omit drops the properties you name. Is Omit<User, "idd">, with a typo, rejected by TypeScript?

No. TypeScript says nothing, and Omit drops nothing. Pick with a wrong property name is rejected, Omit isn't.

Meaning: Pick keeps only the properties you name. Omit drops the ones you name and keeps the rest. The ? (optional) on age stays in the result of Omit.

⚡ Record: keys and values

Write:

const points: Record<string, number> = {};
points["budi"] = 0;
points["ani"] = 0; // { budi: 0, ani: 0 }

Meaning: Record<K, V> is an object with keys (property names) of type K and values of type V. When K is string, the object can start empty and be filled one key at a time. In the exercise, this object is made inside a function, so don't forget to return the object at the end of the function.

What you will learn