DEV Community

Cover image for TypeScript Utility Types: The Complete Guide
Parsa J
Parsa J

Posted on Originally published at bestpractic.org

TypeScript Utility Types: The Complete Guide

You add a field to your User interface. Somewhere three files away, a hand-written UpdateUserInput type — built the week before by copying User and manually marking six fields optional — doesn't get the memo. It still compiles. It's just wrong, and nothing tells you until a form silently drops the new field at runtime.

What you'll learn

By the end of this guide you'll be able to:

  • Explain what a utility type actually is under the hood — not a special compiler feature, just a mapped or conditional type someone wrote once
  • Use Partial, Required, Readonly, Pick, Omit, and Record correctly, including the shallow-ness that trips people up
  • Use Exclude, Extract, NonNullable, ReturnType, Parameters, and Awaited to derive types from other types instead of hand-writing them
  • Recognize why Omit silently drops fields on a union type, and fix it with a two-line distributive version
  • Decide when reaching for a built-in utility type is the right call, and when a hand-written type is clearer

Who this is for: you've written interfaces, functions, and generics in TypeScript, and you've used Partial<T> or Omit<T, K> without being totally sure what they expand to.

Contents

Why utility types exist

Here's the naïve version of the opening story, written out:

interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "member";
}

// hand-written, copy-pasted from User the week before this field existed
interface UpdateUserInput {
  name?: string;
  email?: string;
  role?: "admin" | "member";
  // id intentionally left off — you don't update the id
  // ...and whatever gets added to User next just won't show up here
}
Enter fullscreen mode Exit fullscreen mode

UpdateUserInput isn't connected to User in any way the compiler can see. It's a second, independent type that happens to look similar today. Add avatarUrl to User and UpdateUserInput has no idea — it keeps compiling, keeps passing review, and keeps being wrong.

The fix is to derive the new type from the old one instead of retyping it:

type UpdateUserInput = Partial<Omit<User, "id">>;
// { name?: string; email?: string; role?: ("admin" | "member") | undefined }
Enter fullscreen mode Exit fullscreen mode

Now UpdateUserInput is a computation over User, not a copy of it. Add avatarUrl to User and UpdateUserInput picks it up automatically, still optional, still without id. Partial and Omit are the two utility types doing that work — and they ship with TypeScript's standard library, in lib.es5.d.ts, as plain type aliases you could have written yourself.

The mental model: utility types are just mapped and conditional types

The mental model: a utility type is not a compiler feature — it's an ordinary generic type alias, built from two tools you already have: a mapped type (loop over a type's keys and transform each property) and a conditional type (branch on whether one type is assignable to another). TypeScript ships about twenty of these pre-written so you don't retype them, but nothing stops you from writing your own.

Here's Partial<T> in full — this is close to its real definition in lib.es5.d.ts:

type MyPartial<T> = {
  [K in keyof T]?: T[K];
};
Enter fullscreen mode Exit fullscreen mode

Read it like a for...in loop over types: K in keyof T walks every key of T; ?: adds the optional modifier to each one; T[K] keeps that property's original type. That's the entire mechanism. Required<T> is the same loop with -? (remove the optional modifier) instead of ?. Readonly<T> is the same loop with readonly added. Three "different" utility types, one template, one character changed each time.

Pick and Omit use the same mapped-type loop, but over a narrower or computed set of keys instead of all of keyof T:

type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};

type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;
Enter fullscreen mode Exit fullscreen mode

Omit isn't its own primitive — it's Pick over "every key except these," and "every key except these" is Exclude, a conditional type:

type MyExclude<T, U> = T extends U ? never : T;
Enter fullscreen mode Exit fullscreen mode

Read that as: for each member of T, if it's assignable to U, replace it with never (which then vanishes from a union); otherwise keep it. This single four-word conditional is the engine behind Exclude, Extract, and — as you'll see in the edge cases section — the reason Omit behaves unexpectedly on union types.

Key concept: once you can read [K in keyof T] as "loop over keys" and T extends U ? X : Y as "branch on assignability," every utility type in the standard library is legible on sight. You're not memorizing twenty names — you're applying two patterns.

Stage 1: the modifier types — Partial, Required, Readonly

These three change which modifiers apply to every property, without touching which properties exist.

interface Config {
  host: string;
  port: number;
  debug?: boolean;
}

type PartialConfig = Partial<Config>;
// { host?: string; port?: number; debug?: boolean }

type RequiredConfig = Required<Config>;
// { host: string; port: number; debug: boolean }  — debug's "?" is gone

type ReadonlyConfig = Readonly<Config>;
// { readonly host: string; readonly port: number; readonly debug?: boolean }
Enter fullscreen mode Exit fullscreen mode

Partial is the one you reach for constantly: update payloads, form state before every field is filled in, default-merging ({ ...defaults, ...overrides } where overrides: Partial<Config>). Required is its mirror — useful for asserting that, after validation, every optional field has in fact been filled:

function startServer(config: Required<Config>) {
  // debug is guaranteed defined here — the compiler enforces it at the call site
}
Enter fullscreen mode Exit fullscreen mode

Readonly prevents reassignment of top-level properties:

const c: Readonly<Config> = { host: "localhost", port: 3000 };
c.port = 4000; // Error: Cannot assign to 'port' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

Stage 2: the key-selection types — Pick, Omit, Record

These change which properties exist, keeping their original modifiers and types.

interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "member";
}

type PublicUser = Pick<User, "id" | "name">;
// { id: string; name: string }

type UserWithoutId = Omit<User, "id">;
// { name: string; email: string; role: "admin" | "member" }
Enter fullscreen mode Exit fullscreen mode

Pick says "keep only these keys"; Omit says "keep everything except these keys." Use Pick when the kept set is small and stable (a public-facing subset); use Omit when you're removing one or two fields from an otherwise-large shape and don't want to re-list everything you're keeping.

Record<K, T> builds an object type from a set of keys and a single value type — useful for lookup tables and maps keyed by a known union:

type Role = "admin" | "member" | "guest";

const roleLabels: Record<Role, string> = {
  admin: "Administrator",
  member: "Member",
  guest: "Guest",
};
// omit one key, e.g. "guest", and TypeScript errors: property is missing
Enter fullscreen mode Exit fullscreen mode

That last line is Record's real value over a plain index signature ({ [key: string]: string }): because the key type is a specific union, TypeScript checks that every member of the union has an entry, and rejects keys outside the union entirely.

🎮 Try it yourself

▶️ Open the interactive playground →

Runs right in your browser — poke at it and watch the concept react live.

Stage 3: the conditional types — Exclude, Extract, NonNullable

These operate on unions, not object shapes — think of them as set operations over the members of a union type.

type Status = "idle" | "loading" | "success" | "error";

type NotIdle = Exclude<Status, "idle">;
// "loading" | "success" | "error"

type Settled = Extract<Status, "success" | "error">;
// "success" | "error"

type MaybeUser = User | null | undefined;
type DefiniteUser = NonNullable<MaybeUser>;
// User
Enter fullscreen mode Exit fullscreen mode

Exclude<T, U> keeps the members of T that are not assignable to U; Extract<T, U> keeps the members that are. They're complements of each other over the same two inputs. NonNullable<T> strips null and undefined from T — it used to be defined as Exclude<T, null | undefined>, but since TypeScript 4.8 it's T & {} instead (intersecting with the empty object type cancels null and undefined out, and unlike the old conditional type, the intersection form simplifies cleanly when T is itself generic).

A real use: narrowing a discriminated union after a check that a plain if can't express as a type:

function isSettled(status: Status): status is Extract<Status, "success" | "error"> {
  return status === "success" || status === "error";
}
Enter fullscreen mode Exit fullscreen mode

Stage 4: the introspection types — ReturnType, Parameters, Awaited

These pull a type out of a function signature or a Promise, instead of transforming an object shape.

function createUser(name: string, role: "admin" | "member") {
  return { id: crypto.randomUUID(), name, role };
}

type NewUser = ReturnType<typeof createUser>;
// { id: string; name: string; role: "admin" | "member" }

type CreateUserArgs = Parameters<typeof createUser>;
// [name: string, role: "admin" | "member"]

async function fetchUser(): Promise<User> {
  /* ... */
  return {} as User;
}

type FetchedUser = Awaited<ReturnType<typeof fetchUser>>;
// User — not Promise<User>
Enter fullscreen mode Exit fullscreen mode

These three are the way to keep a type in sync with a function's implementation instead of a parallel hand-written declaration. typeof createUser gets you the function's type; ReturnType and Parameters pull pieces back out of it. Awaited<T> recursively unwraps nested promises (Promise<Promise<User>> still resolves to User), which is what makes Awaited<ReturnType<typeof fetchUser>> correct instead of leaving you with a dangling Promise<User>.

Edge cases and gotchas

Every built-in here is shallow. Partial<T>, Required<T>, and Readonly<T> only touch T's own top-level properties:

interface Profile {
  user: { name: string; email: string };
}

type PartialProfile = Partial<Profile>;
// { user?: { name: string; email: string } }
// user.name and user.email are still required — Partial didn't recurse
const p: PartialProfile = { user: { name: "Ada" } }; // Error: email is missing
Enter fullscreen mode Exit fullscreen mode

If you need every nested field optional too, you need a recursive mapped type (often called DeepPartial) — it isn't in the standard library because "how deep" and "should arrays recurse too" are decisions a one-size-fits-all utility can't make for you.

Readonly is compile-time only. Nothing prevents Object.freeze-style mutation at runtime through an untyped reference, a cast, or library code that doesn't know about your type. Readonly<T> stops your code from writing through that reference; it is not a runtime guarantee.

Omit on a union type silently drops fields it shouldn't. This is the gotcha worth remembering. Recall Omit<T, K> = Pick<T, Exclude<keyof T, K>>. The bug is in what keyof means for a union:

interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; side: number }
type Shape = Circle | Square;

type ShapeWithoutKind = Omit<Shape, "kind">;
// You'd expect: { radius: number } | { side: number }
// You actually get: {}
Enter fullscreen mode Exit fullscreen mode

keyof (Circle | Square) is only the keys common to every member — here, just "kind" — because accessing a property on a union value only type-checks for properties every branch has. So Exclude<keyof Shape, "kind"> excludes the only common key and leaves never, and Pick<Shape, never> is {} for both branches. radius and side were never in the computation to begin with — they're silently gone, and ShapeWithoutKind is {}, not an error.

The fix is a distributive version that applies Omit to each union member separately before they're merged back into a union:

type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
  ? Omit<T, K>
  : never;

type ShapeWithoutKind = DistributiveOmit<Shape, "kind">;
// { radius: number } | { side: number } — correct
Enter fullscreen mode Exit fullscreen mode

The T extends unknown ? ... : never isn't a real check (every type extends unknown) — its only job is to make the conditional distribute over T when T is a union, running Omit once per branch instead of once on the merged type. This is the single most-cited TypeScript utility-type gotcha for a reason: it compiles cleanly and returns a plausible-looking empty object, so it tends to surface as a runtime bug, not a type error.

Best practices

Reach for a built-in utility type when you're deriving a type from one that already exists and is the source of truth — an API response shape, a Prisma/database model, a component's prop type. The derived type should update automatically when the source changes; that's the entire point.

Avoid them when the "derived" type and the source type are only accidentally similar today and will diverge in meaning tomorrow. A LoginFormValues type that happens to share two field names with User isn't a Pick<User, ...> — it's its own type that should be declared as its own type.

Prefer Pick over Omit when the kept set is small (2–3 fields) and stable — it reads as an explicit allowlist and doesn't silently include a field someone adds to the source type later without you noticing. Prefer Omit when you're removing one or two fields from an otherwise-large, evolving shape.

Reach for DistributiveOmit deliberately, not by default — write Omit first, and only swap in the distributive version once you've confirmed the source type is (or might become) a union. Reaching for it reflexively everywhere adds a layer of indirection most object shapes never need.

FAQ

Does Partial<T> make nested object properties optional too?

No. Partial, Required, and Readonly are shallow — they only transform T's own top-level properties. A property whose type is itself an object keeps that object's original required/optional fields untouched. Use a hand-written recursive mapped type if you need every nested level.

Why does Omit return {} on a union type instead of erroring?

Because Omit<T, K> is implemented as Pick<T, Exclude<keyof T, K>>, and keyof on a union type only yields the keys common to every member. If the only common key is the one you're omitting, the key set to keep becomes never, and Pick<T, never> is {}. Use a distributive version (T extends unknown ? Omit<T, K> : never) to get the per-branch result you expect. See "Edge cases and gotchas" above for the full example.

Can I combine utility types, like Partial<Pick<T, K>>?

Yes — they're ordinary generic types, so they compose exactly like function calls. Partial<Pick<User, "name" | "email">> first narrows to two fields, then makes both optional. Order matters: Pick<Partial<User>, "name"> makes everything optional first, then keeps only name (still optional) — a different, usually less useful, result for this case.

What's the difference between Record<string, T> and an index signature?

For a plain string key type they behave almost identically — Record<string, T> is defined using an index signature internally. The difference matters when the key type is a specific union: Record<Role, string> checks that every member of Role has an entry and rejects extra keys, while { [key: string]: string } accepts any string key and enforces nothing about which keys must be present.

Does TypeScript have a built-in DeepPartial or DeepReadonly?

No. The standard library intentionally ships only shallow versions, because "how deep," "should this recurse into arrays and Map/Set," and "should functions be left alone" are decisions that vary by use case. Write your own recursive mapped type, or use a small, well-tested library version if you need one across a codebase.

Cheat sheet

Task Code Notes
Make every property optional Partial<T> Shallow — nested objects keep their original required fields
Make every property required Required<T> Removes the ? modifier everywhere, shallow
Make every property readonly Readonly<T> Compile-time only, shallow, no runtime freeze
Keep only some properties `Pick<T, "a" \ "b">`
Remove some properties `Omit<T, "a" \ "b">`
Omit on a union, correctly T extends unknown ? Omit<T, K> : never Forces per-branch distribution
Build a lookup object type Record<K, T> K a union enforces every key is present and no extra keys
Keep union members assignable to U Extract<T, U>
Remove union members assignable to U Exclude<T, U> Complement of Extract
Strip null/undefined from a type NonNullable<T> T & {} since TS 4.8 (was `Exclude<T, null \
Get a function's return type {% raw %}ReturnType<typeof fn> Use typeof fn, not fn, to reference the function's type
Get a function's parameter tuple Parameters<typeof fn>
Unwrap a (possibly nested) Promise Awaited<T> Awaited<ReturnType<typeof asyncFn>> gives the resolved value's type
// the whole pattern, copy-paste ready
interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "member";
}

// derive, don't retype
type PublicUser = Pick<User, "id" | "name">;
type UpdateUserInput = Partial<Omit<User, "id">>;
type UserMap = Record<string, User>;

type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
  ? Omit<T, K>
  : never;
Enter fullscreen mode Exit fullscreen mode

🧠 Test yourself

Think it clicked? Take the 8-question quiz →

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

Key takeaways

  • A utility type is a mapped type ([K in keyof T]) or a conditional type (T extends U ? X : Y) someone already wrote — not a special compiler feature. You can write your own.
  • Partial, Required, and Readonly change modifiers; Pick, Omit, and Record change which keys exist; Exclude/Extract/NonNullable operate on unions; ReturnType/Parameters/Awaited pull types out of function signatures.
  • Every built-in here is shallow — nested objects are untouched unless you write a recursive version yourself.
  • Omit on a union type can silently collapse to {}. If the source type might be a union, use a distributive Omit.

That UpdateUserInput from the opening — the one that quietly missed a field — was never going to catch up to User by being retyped more carefully. It needed to stop being its own type and become a computation over User instead. That's what every utility type in this guide is: not a list of twenty names to memorize, but two small tools — loop over keys, branch on assignability — applied again and again.

Which one bit you first: the shallow Partial, or the union Omit? Tell me in the comments — I'll compile the most common one into next week's "gotchas" post.

📚 Read next


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Top comments (0)