Utility types

Topic 3 of 6 in Type operators7 min readIntermediateFree course

Overview

Real applications need many variations of the same type: a User from the database, the input for creating a user (no id yet), an update where every field is optional, a public version without the email. Writing each by hand duplicates the model. TypeScript ships with utility types that build these variations for you.

Built-in utility types, starting from type User = { id: number; name: string; email: string; bio?: string }. Partial<User> makes every property optional. Required<User> makes every property required, including bio. Readonly<User> makes nothing reassignable. Pick<User, “id” | “name”> gives { id; name }. Omit<User, “email”> gives { id; name; bio? }. Also: Record<K, V> — an object type from keys and a value; ReturnType<typeof fn> — what a function returns; Parameters<typeof fn> — its parameters as a tuple; Awaited<Promise<T>> — the value inside a promise; NonNullable<T> — removes null and undefined; Exclude and Extract — filter the members of a union. Utility types build new types from existing ones, so related types never drift apart.

All of these are generic types defined in TypeScript’s standard library — and in the next lessons you’ll learn to write them yourself.

Changing modifiers: Partial, Required, Readonly

TypeScript
type User = { id: number; name: string; email: string; bio?: string };

type UserDraft = Partial<User>;    // every property optional
type FullUser = Required<User>;    // bio is now required too
type FrozenUser = Readonly<User>;  // every property readonly

Partial is the classic type for updates:

TypeScript
function updateUser(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}

updateUser(user, { name: "Asha R." });   // ✓ any subset

Readonly is shallow: nested objects and arrays inside can still be changed.

Selecting properties: Pick and Omit

TypeScript
type UserPreview = Pick<User, "id" | "name">;       // { id: number; name: string }
type NewUser = Omit<User, "id">;                    // { name; email; bio? }

Combine them for precise variants:

TypeScript
// Only these fields may be updated, and each is optional
type UserUpdate = Partial<Pick<User, "name" | "email" | "bio">>;

Pick checks its keys (Pick<User, "phone"> is an error); Omit accepts any string, so a typo in Omit silently removes nothing. Double-check Omit keys.

Building object types: Record

Record<K, V> — covered in Index signatures and records — creates an object type with keys K and values V:

TypeScript
type Permissions = Record<User["role"], string[]>;

Filtering unions: Exclude, Extract, NonNullable

These work on unions, removing or keeping members:

TypeScript
type Role = "admin" | "editor" | "guest";

type StaffRole = Exclude<Role, "guest">;             // "admin" | "editor"
type Elevated = Extract<Role, "admin" | "owner">;    // "admin"

type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>;                  // string

Exclude and Extract also filter by shape: Extract<Shape, { kind: "circle" }> picks the circle member out of a discriminated union.

Types from functions: ReturnType, Parameters, Awaited

TypeScript
function createSession(userId: number, remember = false) {
  return { token: crypto.randomUUID(), userId, expires: new Date() };
}

type Session = ReturnType<typeof createSession>;
type SessionArgs = Parameters<typeof createSession>;   // [userId: number, remember?: boolean]

For async functions, ReturnType gives a Promise<…>; Awaited unwraps it:

TypeScript
async function fetchUser(id: number) { … return user; }

type Pending = ReturnType<typeof fetchUser>;           // Promise<User>
type Loaded = Awaited<ReturnType<typeof fetchUser>>;   // User

These are invaluable when a library exports a function but not the types of its arguments or results.

More you’ll meet

Utility Does
ConstructorParameters<typeof C> a class constructor’s parameters
InstanceType<typeof C> the instance type of a class
NoInfer<T> stops TypeScript inferring a type parameter from this position
Uppercase<S>, Lowercase<S>, Capitalize<S> change the case of string literal types (Template literal types)

Composing utilities

Utility types nest. Read them inside-out:

TypeScript
type EditableProfile = Readonly<Pick<User, "id">> & Partial<Omit<User, "id">>;
// id is readonly and required; everything else optional

If a composition gets hard to read, give each step a name:

TypeScript
type UserKey = Pick<User, "id">;
type UserFields = Omit<User, "id">;
type EditableProfile = Readonly<UserKey> & Partial<UserFields>;

A typical set of model types

TypeScript
type Product = { id: string; name: string; price: number; createdAt: Date };

type NewProduct = Omit<Product, "id" | "createdAt">;       // POST body
type ProductUpdate = Partial<NewProduct>;                  // PATCH body
type ProductSummary = Pick<Product, "id" | "name">;        // list view

One model, every variant derived — add a field to Product and the create, update and summary types all follow. You’ll use exactly this pattern in the final project.

Remember: write the main type once, then derive variations with Partial, Pick, Omit, Readonly, Exclude and friends. If you’re copying properties between types, there’s probably a utility for it.

Exercise

Types for a user service

From the single User type, derive (don’t rewrite!): NewUser — everything except id and createdAt (Omit); UserUpdate — any subset of name, email and role (Partial + Pick); PublicUser — only id, name and role (Pick); FrozenUser (Readonly); StaffRole — the roles except "guest" (Exclude). Write createUser(input: NewUser, id: number): User, updateUser(user: User, changes: UserUpdate): User, toPublic(user: User): PublicUser and isStaff(role: User["role"]): role is StaffRole. Use them and print the results. Also derive type Loaded = Awaited<ReturnType<typeof loadUser>> for the given async function. Show with // @ts-expect-error that an update can’t change id and a FrozenUser can’t be modified.

TypeScript
type User = {
  id: number;
  name: string;
  email: string;
  role: "admin" | "editor" | "guest";
  createdAt: Date;
};

async function loadUser(id: number) {
  return { id, name: "Loaded", email: "l@example.com", role: "guest" as const, createdAt: new Date(0) };
}

// Derived types

// Functions

Summary

  • Utility types transform existing types: Partial, Required and Readonly change every property’s modifiers.
  • Pick<T, Keys> keeps some properties, Omit<T, Keys> removes some — perfect for create/update/public variants.
  • Exclude, Extract and NonNullable filter union members.
  • ReturnType, Parameters and Awaited derive types from functions and promises.
  • Derived types stay in sync: change the base type and every variant updates.