Utility types for objects

Intermediate · 22 min

Partial, Required, Readonly, Pick, Omit and Record: deriving update payloads, public views and lookup tables from one model instead of copying it.

Before thisIndexed access typesObject types, optional and readonly propertiesReadonly and immutabilityIndex signatures and Record

Web Dev Simplified · 22 min · from 1:48

Utility types for objects

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Built-in utility types turn one model into the variations an app needs (create payloads, patches, public views) so each variation updates when the model does.
  • `Partial<T>` makes every property optional and `Required<T>` makes every property required; both apply to the top level only.
  • `Readonly<T>` marks every top-level property `readonly`, which blocks reassignment at compile time but neither freezes the object at runtime nor protects nested objects.
  • `Pick<T, K>` keeps the listed keys and `Omit<T, K>` drops them; `Pick` rejects a key that doesn't exist on `T`, but `Omit` accepts any string, so a typo in `Omit` silently removes nothing.
  • `Record<K, V>` builds an object type with keys `K` and values `V`; with a union of literal keys it forces every key to be present, which makes it a checked lookup table.
  • Utility types compose, as in `Partial<Omit<User, "id">>`, and they're ordinary mapped types from the standard library rather than compiler magic.

One model, many shapes

A real app rarely uses a model in just one shape. Take a user:

interface User {
  id: string;
  email: string;
  name: string;
  passwordHash: string;
  bio?: string;
}

The signup form sends everything except id. A profile update sends only the fields that changed. The public profile page must never see passwordHash. Write each of those as its own interface and you have four copies of the user to keep in step.

TypeScript ships a set of generic types that produce these variations from User directly. They’re called utility types, and they’re available everywhere with no import. Think of them as the standard transformations a print shop offers: same original, different cuts.

Partial and Required

Partial<T> makes every property optional. That’s the shape of a patch:

function updateUser(id: string, patch: Partial<User>) {
  // send only the changed fields
}

updateUser("u_1", { bio: "Writes TypeScript" }); // fine

Required<T> goes the other way and removes every ?. It suits a value where defaults have already been filled in:

interface Options {
  retries?: number;
  timeoutMs?: number;
}

function resolveOptions(opts: Options): Required<Options> {
  return { retries: opts.retries ?? 3, timeoutMs: opts.timeoutMs ?? 5000 };
}

const resolved = resolveOptions({ retries: 5 });
resolved.timeoutMs.toFixed(0); // no undefined check needed

Callers still pass a loose Options; everything downstream gets a value with no holes. Both utilities act on top-level properties only. A nested object keeps its own optional or required fields.

Readonly

Readonly<T> marks every top-level property readonly:

interface Order {
  id: string;
  items: { sku: string; quantity: number }[];
}

function render(order: Readonly<Order>) {
  order.id = "changed"; // Error: 'id' is a read-only property
  order.items[0].quantity = 99; // allowed: Readonly is shallow
}

Two limits apply, both covered in readonly and immutability. It is shallow, so items can’t be reassigned but its contents can change. And it exists only at compile time; nothing stops plain JavaScript code from mutating the object.

Pick and Omit

Pick<T, K> keeps the keys you list. Omit<T, K> keeps everything except them. Use whichever list is shorter:

type UserSummary = Pick<User, "id" | "name">; // { id: string; name: string }
type PublicUser = Omit<User, "passwordHash" | "email">;
type NewUser = Omit<User, "id">;

They differ in one way that bites people. Pick requires its keys to be keyof T. Omit accepts any string:

type PickTypo = Pick<User, "pasword">; // Error: does not satisfy the constraint 'keyof User'
type OmitTypo = Omit<User, "pasword">; // no error, and nothing was removed

OmitTypo still contains passwordHash. When an Omit exists to keep a secret field out of a response, double-check the spelling, or define a stricter helper such as type StrictOmit<T, K extends keyof T> = Omit<T, K> that rejects unknown keys.

Record

Record<K, V> builds an object type whose keys are K and whose values are V. With a union of literal keys, it becomes a checked lookup table:

type Role = "viewer" | "editor" | "owner";

const permissions: Record<Role, string[]> = {
  viewer: ["read"],
  editor: ["read", "write"],
  owner: ["read", "write", "delete"],
};

const labels: Record<Role, string> = { // Error: property 'owner' is missing
  viewer: "Viewer",
  editor: "Editor",
};

Add a fourth role to the union and every Record<Role, ...> table in the codebase fails to compile until it handles the new role. Record<string, V> is a different thing, an index signature with no required keys, as covered in index signatures and Record.

They compose

Each utility takes a type and returns a type, so you can nest them. The safest patch type for updateUser drops the fields nobody should edit, then makes the rest optional:

type UserPatch = Partial<Omit<User, "id" | "passwordHash">>;

const patch: UserPatch = { name: "Ada" }; // fine
const sneaky: UserPatch = { id: "u_2" }; // Error: 'id' does not exist in type

None of these are special to the compiler. Partial<T> is defined in the standard library as { [P in keyof T]?: T[P] }, built from keyof and the indexed access types of the last two lessons. Mapped types shows how to write your own.

About the video

The embed starts at 1:48, where Kyle Cook of Web Dev Simplified begins on the object utilities. The section up to 10:05 covers Pick, Omit, Partial, Required, Readonly and Record with realistic examples, which is this lesson’s list. The rest of the video moves on to the union and function utilities, which is the next lesson, so you can stop at 10:05 or keep going. Dave Gray’s video below is a slower, beginner-paced alternative.

Check yourself

  1. 01Why is `Partial<User>` a poor type for a PATCH request body on its own, and how would you tighten it?

    `Partial<User>` makes every field optional, including ones clients must never change, such as `id`. `Partial<Omit<User, "id" | "passwordHash">>` first removes the fields that shouldn't be editable, then makes the remaining ones optional.

  2. 02`type PublicUser = Omit<User, "pasword">` compiles without error. What went wrong?

    The key is misspelled. `Omit` constrains its keys only to `string | number | symbol`, not to `keyof User`, so an unknown key is accepted and simply matches nothing. `passwordHash` stays in `PublicUser`. `Pick` would have caught the same typo because its keys must be `keyof T`.

  3. 03You pass a `Readonly<Order>` to a function. Can the function change `order.items[0].quantity`?

    Yes. `Readonly<T>` is shallow, so `order.items` can't be reassigned, but the array and the objects inside it are still mutable. It also has no runtime effect. Protecting nested data needs readonly array types or a recursive readonly type, and `Object.freeze` if it must hold at runtime.

  4. 04What does `Record<"viewer" | "editor", string[]>` require that `Record<string, string[]>` doesn't?

    With a union of literal keys, the object must contain exactly those keys, so leaving out `editor` is a compile error. `Record<string, string[]>` is an index signature that allows any number of string keys, including none.

  5. 05When would `Required<Options>` be the right return type for a function?

    When the function fills in a default for every optional field, as a resolved config does. Callers can then read each option without checking for `undefined`, while the input type stays `Options` with its optional fields.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark