Sub topic 6
Composing utility types
This chapter assumes you know the basic utility types from earlier chapters (Partial, Pick, Omit, Required, Readonly), the syntax of generics such as Array<T>, and union and string literal types. Here you will combine those types to describe the shapes an application actually needs. You will also learn the ways composition can fail without an error.
Why compose
One interface rarely matches every place its data is used. A User has an id the server assigns, fields a client sends when creating it, and a smaller subset shown in a list. You could write a separate interface for each use. Those copies drift apart as soon as someone adds a field to User and forgets the others.
Composition derives each shape from a single source of truth. A change to User flows into every derived type, and the compiler flags the places that no longer fit.
Reading a composition from the inside out
A nested utility type is a pipeline. The innermost type runs first, and each outer type transforms the result.
interface User {
id: number;
name: string;
email: string;
createdAt: Date;
}
type UserUpdate = Partial<Omit<User, "id" | "createdAt">>;Read UserUpdate in this order:
Omit<User, "id" | "createdAt">gives{ name: string; email: string }.Partial<...>makes both remaining properties optional.
The result is { name?: string; email?: string }. A caller can send any subset of the editable fields and cannot touch id or createdAt.
Three payloads from one interface
Most applications need the same three derived shapes. This example builds them and uses them.
interface User {
id: number;
name: string;
email: string;
createdAt: Date;
}
type ServerFields = "id" | "createdAt";
type NewUser = Omit<User, ServerFields>;
type UserUpdate = Partial<NewUser>;
type UserSummary = Readonly<Pick<User, "id" | "name">>;
function applyUpdate(user: User, changes: UserUpdate): User {
return { ...user, ...changes };
}
const ada: User = {
id: 1,
name: "Ada",
email: "[email protected]",
createdAt: new Date(0),
};
const renamed = applyUpdate(ada, { name: "Ada Lovelace" });
const summary: UserSummary = { id: renamed.id, name: renamed.name };
console.log(renamed.name, summary);Naming the shared piece, ServerFields, keeps the rules in one place. UserUpdate is defined as Partial<NewUser>, so it follows NewUser automatically. If you later add phone: string to User, both types pick it up with no further edits.
Wrapping a composition in a generic helper
When the same combination appears more than twice, give it a name with a type parameter.
type Patch<T, ReadOnlyKeys extends keyof T> = Partial<Omit<T, ReadOnlyKeys>>;
interface Product {
sku: string;
title: string;
price: number;
}
type ProductPatch = Patch<Product, "sku">;
const change: ProductPatch = { price: 19.99 };
console.log(change);The constraint ReadOnlyKeys extends keyof T makes the compiler reject keys that do not exist on T. That constraint matters, as the pitfalls section below shows.
Making only some properties optional or required
Partial<T> and Required<T> act on every property. You often want to change just a few. The usual recipe splits the type, transforms one part, and joins the parts with an intersection.
interface User {
id: number;
name: string;
email: string;
createdAt: Date;
}
interface Profile {
id: number;
nickname?: string;
bio?: string;
}
type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type WithRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
type Draft = WithOptional<User, "email" | "createdAt">;
type PublicProfile = WithRequired<Profile, "nickname">;
const draft: Draft = { id: 1, name: "Ada" };
const profile: PublicProfile = { id: 1, nickname: "ada" };
// const missing: PublicProfile = { id: 2 }; // Error: Property 'nickname' is missing
console.log(draft, profile);WithOptional removes email and createdAt, then adds them back as optional. WithRequired intersects Profile with a type in which nickname is mandatory. The intersection of nickname?: string and nickname: string is a required string.
Flattening the display
Hovering over Draft in an editor shows Omit<User, ...> & Partial<Pick<User, ...>>. That is correct but hard to read. A small helper forces the compiler to show a single flat object type.
type Prettify<T> = { [K in keyof T]: T[K] } & {};
interface User {
id: number;
name: string;
email: string;
}
type WithOptional<T, K extends keyof T> = Prettify<
Omit<T, K> & Partial<Pick<T, K>>
>;
type Draft = WithOptional<User, "email">; // { id: number; name: string; email?: string }
const draft: Draft = { id: 1, name: "Ada" };
console.log(draft);Prettify changes only how the type is displayed. It does not change which values the type accepts.
Order matters when modifiers conflict
Most compositions give the same result in either order. Partial<Pick<T, K>> and Pick<Partial<T>, K> both produce the same type. Order does matter when two utility types push the same modifier in opposite directions, because the outer one wins.
interface Config {
host: string;
port?: number;
}
type AllRequired = Required<Partial<Config>>; // { host: string; port: number }
type AllOptional = Partial<Required<Config>>; // { host?: string; port?: number }
const a: AllRequired = { host: "localhost", port: 8080 };
const b: AllOptional = {};
console.log(a, b);In AllRequired, Partial makes everything optional and the outer Required then makes everything mandatory. The original distinction between host and port is gone. Whenever you stack Partial, Required and Readonly, read from the inside out and expect the outermost modifier to decide the result.
| Composition | Resulting properties |
|---|---|
| `Partial<Omit<T, K>>` | All except `K`, all optional |
| `Required<Pick<T, K>>` | Only `K`, all mandatory |
| `Readonly<Pick<T, K>>` | Only `K`, cannot be reassigned |
| `Omit<T, K> & Partial<Pick<T, K>>` | All properties, only `K` optional |
| `Required<Partial<T>>` | All properties, all mandatory |
Pitfalls specific to composition
Omit accepts keys that do not exist
Pick requires its keys to exist on the type. Omit does not. Its second parameter is constrained only to keyof any, so a misspelled key is accepted and silently removes nothing.
interface User {
id: number;
name: string;
}
type Oops = Omit<User, "idd">; // no error: still { id: number; name: string }
type StrictOmit<T, K extends keyof T> = Omit<T, K>;
// type Bad = StrictOmit<User, "idd">;
// Error: Type '"idd"' does not satisfy the constraint 'keyof User'.
type Good = StrictOmit<User, "id">; // { name: string }
const user: Good = { name: "Ada" };
console.log(user);The typo in Oops is dangerous in a pipeline such as Partial<Omit<User, "idd">>. The type looks safe, but id stays editable. Prefer StrictOmit, or a constrained helper like Patch above, when the key list is written by hand.
Modifiers stay shallow
Every modifier in this chapter works on the top level only. Readonly<Settings> stops you from reassigning settings.theme, but not from changing settings.theme.color.
interface Settings {
theme: { color: string };
}
const settings: Readonly<Settings> = { theme: { color: "red" } };
// settings.theme = { color: "blue" }; // Error: read-only property
settings.theme.color = "blue"; // allowed: the nested object is not read-only
console.log(settings);Nested cases need a recursive custom type, which a later chapter covers.
Omit and Pick on unions
When T is a union, keyof T contains only the keys that every member shares. Omit<T, K> is therefore computed against that shared set, so member-specific properties disappear. Compose a distributive version over such types rather than applying Omit directly. This chapter only flags the problem. The limits chapter handles it in full.
Deep compositions are hard to debug
A chain of four or five utility types is hard to read and produces unhelpful error messages. Two habits help:
- Give intermediate steps names, as
ServerFieldsandNewUserdid above. - Wrap the final result in
Prettifyso hovering shows the actual properties.
Choosing a composition
Start from the shape you need and work backward:
- Decide which properties the new type contains. Use
Pickto keep a few, orOmit(preferably constrained) to drop a few. - Decide whether each remaining property is required or optional. Use
PartialorRequiredif they all behave the same way. Otherwise split with an intersection. - Decide whether the receiver may modify values. Add
Readonlylast, since it does not affect which properties exist. - Name the result, and check it by hovering or with a test value.
Exercise
Given interface Article { id: number; title: string; body: string; published: boolean; }, write a type ArticleEdit for an edit form in which id cannot be sent, title and body may each be omitted, and published is not editable. Use a single composition of built-in utility types.
Show answer
type ArticleEdit = Partial<Pick<Article, "title" | "body">>; This keeps only title and body, then makes both optional. Partial<Omit<Article, "id" | "published">> gives the same result, but Pick is safer here because a misspelled key is an error.
Exercise
What are the types of A and B below, and why do they differ?
interface Options { debug: boolean; level?: number }
type A = Required<Partial<Options>>;
type B = Partial<Required<Options>>;
Show answer
A is { debug: boolean; level: number } and B is { debug?: boolean; level?: number }. When modifiers conflict, the outer utility type decides: Required in A makes every property mandatory after Partial has made them optional, and Partial in B makes every property optional after Required has made them mandatory.
Exercise
A teammate writes type Safe = Partial<Omit<User, "emial">> to make every property except email optional. Describe two problems with this type.
Show answer
First, Omit does not check that its key exists, so the misspelled "emial" raises no error and removes nothing. Second, even with the spelling fixed, the type would drop email entirely and make everything else optional, which is not the stated intent. A correct version is Omit<User, "email"> & Partial<Pick<User, "email">> only if email should be the optional one. To make everything except email optional, use Pick<User, "email"> & Partial<Omit<User, "email">>, and constrain the key with keyof User, for example through StrictOmit.