Sub topic 1
Why utility types exist
Utility types are generic types that TypeScript ships with the language. Each one takes an existing type and produces a new, related type. This chapter explains the problem they solve and how to think about them. It also gives a map of the whole family, so the later chapters on each type have a place to attach.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript syntax: type annotations, interfaces and type aliases.
- Union types and string literal types, such as
"admin" | "editor". - Generic syntax such as
Array<T>, where a type is passed in angle brackets.
You do not need to know mapped types or conditional types yet. A later chapter covers how utility types are built, and this chapter only previews it.
The problem: types that describe the same thing
Real programs describe one concept in several shapes. A user record in a database has an id. A sign-up form has no id yet. A list page needs only the id and the name. An edit form may change any field except the id.
The obvious approach is to write a separate interface for each shape:
interface User {
id: number;
name: string;
email: string;
}
interface NewUser {
name: string;
email: string;
}
interface UserPreview {
id: number;
name: string;
}
interface UserPatch {
name?: string;
email?: string;
}This compiles, and it is wrong in a slow, quiet way. The four interfaces are unrelated as far as the compiler knows. Suppose a teammate renames email to emailAddress in User. TypeScript does not complain about NewUser or UserPatch. Code that builds a NewUser keeps compiling, and it fails later when the data reaches code that expects emailAddress.
Duplicated types create the same drift problem as duplicated code. The fix is also the same: keep one source of truth and derive everything else from it.
Deriving instead of copying
Utility types let you state the relationship between shapes instead of retyping the fields:
interface User {
id: number;
name: string;
email: string;
}
type NewUser = Omit<User, "id">;
type UserPreview = Pick<User, "id" | "name">;
type UserPatch = Partial<NewUser>;
const draft: NewUser = { name: "Ada", email: "[email protected]" };
const preview: UserPreview = { id: 1, name: "Ada" };
const patch: UserPatch = { email: "[email protected]" };Each alias now reads as a sentence. NewUser is a User without id. UserPreview is a User reduced to id and name. UserPatch is a NewUser where every field is optional.
Now repeat the rename. If email becomes emailAddress in User, all three derived types change with it. Any code that still writes email fails at compile time, at the line that is out of date. The compiler does the bookkeeping that a reviewer would otherwise have to do by hand.
What a utility type is
A utility type is a generic type alias. You write its name, pass type arguments in angle brackets, and get a type back. Three facts about them matter in practice:
- They are global. The compiler's standard library declares them, so you use
Partial<User>without an import. - They exist only at compile time. Types are erased when TypeScript is turned into JavaScript. Using
PickorRecordadds no code and no runtime cost. - They are ordinary TypeScript. Most are one or two lines long, built from features you can use yourself. For example,
Partialis defined as a mapped type:
type Partial<T> = {
[P in keyof T]?: T[P];
};You do not need to read that definition yet. The point is that no magic is involved, and a later chapter returns to it. Knowing that utility types are plain code helps when you hit a case they do not cover, because you can write your own version.
A map of the family
The built-in utility types fall into three groups, based on what they take as input.
| Group | Utility types | What they do |
|---|---|---|
| Reshape an object type | `Partial`, `Required`, `Readonly`, `Pick`, `Omit`, `Record` | Change which properties exist, whether they are optional, or whether they can be reassigned |
| Filter a union | `Exclude`, `Extract`, `NonNullable` | Keep or remove members of a union type |
| Read a function or Promise | `ReturnType`, `Parameters`, `Awaited` | Pull a type out of an existing function or Promise instead of rewriting it |
Reshaping object types
These are the ones you will use most.
Partial<T>makes every property optional. It suits update payloads.Required<T>does the opposite and makes every property mandatory.Readonly<T>blocks reassignment of properties.Pick<T, K>keeps only the listed keys.Omit<T, K>removes the listed keys.Record<K, V>builds an object type with the keysK, each holding a value of typeV.
Filtering unions
A union is a set of types, and these utilities treat it that way:
type Status = "idle" | "loading" | "error" | "done";
type Active = Exclude<Status, "idle">;
// "loading" | "error" | "done"
type Finished = Extract<Status, "done" | "error">;
// "error" | "done"
type Name = NonNullable<string | null | undefined>;
// stringExclude removes members, Extract keeps members, and NonNullable removes null and undefined.
Reading function types
Functions already carry type information. ReturnType and Parameters reuse it instead of making you copy it:
function getUser(id: number) {
return { id, name: "Ada" };
}
type UserResult = ReturnType<typeof getUser>;
// { id: number; name: string }
type GetUserArgs = Parameters<typeof getUser>;
// [id: number]If getUser later returns an extra field, UserResult includes it with no edit. Awaited does the same for the value inside a Promise, so Awaited<ReturnType<typeof fetchUser>> gives the resolved result of an async function.
Choosing by what you want to say
Start from the relationship you want to express, then pick the utility that states it.
| You want to say | Use |
|---|---|
| "The same, but every field may be missing" | `Partial<T>` |
| "The same, but nothing may be missing" | `Required<T>` |
| "The same, but nobody may change it" | `Readonly<T>` |
| "Only these fields" | `Pick<T, K>` |
| "Everything except these fields" | `Omit<T, K>` |
| "One value of type V for each key in K" | `Record<K, V>` |
| "This union without some members" | `Exclude<U, M>` |
| "Only these members of the union" | `Extract<U, M>` |
| "What this function gives back" | `ReturnType<typeof fn>` |
Two choices come up often enough to settle early.
Pick and Omit are two views of the same idea. Use Pick when the result is a short list of fields you want, and Omit when it is a long type missing one or two. The deciding factor is what happens when User gains a field. A Pick result stays the same size, while an Omit result grows. Choose the behavior you want a new field to have.
Utility types can also be stacked. Partial<Omit<User, "id">> is a type where id is gone and the rest are optional. Composition has its own chapter.
When not to use them
Utility types are a tool for keeping related types in sync. They are not always the better choice.
- When the types are only coincidentally similar. If two shapes happen to share fields today but change for unrelated reasons, linking them creates a coupling you do not want. A change to one type then silently changes the other.
- When the derived type becomes hard to read. A chain of four nested utilities can be harder to understand than a small interface written out by hand. Give the result a name with
type, and keep the name meaningful. - When the built-in does not do what the name suggests. For example,
Partialis shallow andOmitdoes not distribute over unions. The pitfalls chapter covers these cases.
What the rest of the tutorial covers
The following chapters take the groups above one at a time, with Partial, Pick and Omit, and Record first, since they appear in most codebases. Later chapters cover keyof, indexed access types and mapped types, which are the building blocks behind every utility type in the table. With those you can write your own utilities, such as a recursive DeepPartial, and recognize where the built-ins fall short.
Exercises
Exercise
An app defines interface Product { sku: string; title: string; price: number }. A teammate also wrote interface ProductSummary { sku: string; title: string } by hand. Later someone renames title to name in Product. What goes wrong, and how would you define ProductSummary so the problem cannot happen?
Show answer
Nothing in the compiler connects the two interfaces, so ProductSummary keeps its old title field and code that builds or reads summaries is not flagged as out of date. Derive it instead: type ProductSummary = Pick<Product, "sku" | "title">. Then the rename makes the "title" key in the Pick an error right away, and you fix it in one place.
Exercise
Using only the utility types named in this chapter, write a type ProductPatch for an update payload that may change any field of Product except sku, where every field is optional.
Show answer
type ProductPatch = Partial<Omit<Product, "sku">>; Omit removes sku, and Partial makes the remaining fields optional.
Exercise
A utility type like Pick<User, "id"> appears in your source. Does it add any code to the compiled JavaScript? Explain.
Show answer
No. Utility types are type-level only, and TypeScript erases all types when it emits JavaScript, so they have no runtime cost.