The Analogy: The Print Room at the Drawing Office
The drawing office keeps one master tracing for every part, drawn once and filed as the single source of truth, and the print room next door never redraws it. When a department needs a copy it does not sketch the part afresh; it hands the master to the print room and names a standard setting, and the machine produces a print derived from the master by that setting. Change the master tracing and every print made from it afterwards carries the change, because a print was never an independent drawing, only the master seen through one fixed transformation.
The settings come in a small, named set that everyone knows. A full copy reproduces the master as it stands. A provisional print runs the machine in soft pencil, so every dimension box is allowed to be left blank for a draughtsman to fill in later. A checking print does the opposite: it refuses to issue until every box on the master has been inked, so nothing incomplete leaves the room. And a controlled print comes out stamped MASTER, DO NOT MARK, on paper that takes no pencil, for the parts of the shop that must read a figure and never alter it. Each is the same master through a different transformer, not a different drawing.
Two more settings do not copy the whole sheet but a chosen part of it. One prints only the views you name, a single detail lifted off a crowded sheet; the other prints everything except the views you name, the full drawing with the costing block masked out. Both are still generated from the master, so both track it, and if you name a view that is not on the master the counter clerk stops you before the machine runs, because you cannot extract a detail the part does not have. That refusal is the same guarantee the drive square gave the sockets: whatever comes out is a genuine view of this master.
The failure mode is treating a print as if it were the master. A draughtsman pencils a corrected dimension onto a provisional print, files the print, and never carries the change back to the master tracing; the next re-run of any setting comes off the unchanged master and the correction is gone, or worse, two prints of the same part now disagree. And a masked extract with the costing block dropped is read on the shop floor as proof the part has no cost, when the cost is right there on the master and was only hidden for this one print. A copy edited in place, or mistaken for the whole truth, is how a single source of truth quietly stops being one.
Syntax or Core Structure
A utility type is a standard transformer applied to an existing type: Partial<T> makes every property optional, Readonly<T> freezes every property, Pick<T, K> keeps only the named keys, Omit<T, K> drops the named keys. Each is derived from T, so a change to T flows through every one.
// src/prints.ts
interface Part {
code: string;
name: string;
grade: number;
}
type DraftPart = Partial<Part>; // every field optional
type LockedPart = Readonly<Part>; // every field frozen
type IdOnly = Pick<Part, "code">; // just the code
type NoGrade = Omit<Part, "grade">; // everything but grade
const draft: DraftPart = { code: "BR-5" }; // name and grade omitted
const locked: LockedPart = { code: "WS-2", name: "washer", grade: 6 };
const idOnly: IdOnly = { code: "CL-3" };
const noGrade: NoGrade = { code: "PN-9", name: "pin" };
// locked.grade = 9; // refused: grade is read-only on LockedPart
console.log(draft.code, draft.grade ?? "n/a");
console.log(locked.code, locked.name, locked.grade);
console.log(Object.keys(idOnly).length, Object.keys(noGrade).length);
Output:
BR-5 n/a
WS-2 washer 6
1 2
Output (tsc, for the commented line):
error TS2540: Cannot assign to 'grade' because it is a read-only property.
draft is Partial<Part>, so it satisfies the type with only code, and reading grade back gives undefined. locked is Readonly<Part>, so the commented assignment is refused. idOnly kept one key and noGrade kept two, because Pick and Omit sliced the master rather than copying it whole. None of the four types was hand-written; each is Part through a transformer, and editing Part reshapes all of them at once.
Technical Depth: The Transformers, and Where They Leak
Two of these are near-inverses, two slice by key with different strictness, and two read a type off a function. Each is a standard operation on a type, and one of them checks its key argument less carefully than you would expect.
Partial and Required are near-inverses
Partial<T> adds the question mark to every property; Required<T> strips it off again, and also removes undefined from the property's type. They round-trip, but only near enough that you should not lean on it: Required<Partial<T>> gives back T's keys as required, but a property originally typed string | undefined comes back plain string.
// src/roundtrip.ts
interface Spec { code: string; grade: number }
type Loose = Partial<Spec>; // { code?: string; grade?: number }
type Tight = Required<Loose>; // { code: string; grade: number }
const loose: Loose = { code: "BR-5" }; // grade may be absent
const tight: Tight = { code: "WS-2", grade: 6 }; // both required
// const bad: Tight = { code: "CL-3" }; // refused: grade is missing
console.log(loose.code, loose.grade ?? "n/a");
console.log(tight.code, tight.grade);
Output:
BR-5 n/a
WS-2 6
Loose accepts the object with no grade; Tight puts the requirement back, so the commented bad is refused for the same reason a checking print will not issue with a blank box. Partial is the provisional print and Required the checking print, and the pair is how one master type serves both a lenient update payload and a strict validated record.
Pick checks its keys; Omit does not
Pick<T, K> constrains K to keyof T, so a key that is not on the type is refused at compile time. Omit<T, K> does not: its key parameter is keyof any, so a mistyped key compiles silently and simply removes nothing, handing you back the whole type when you meant to drop a field.
// src/keyed.ts
interface Part { code: string; name: string; grade: number; cost: number }
type Two = Pick<Part, "code" | "name">; // exactly two keys
type NoCost = Omit<Part, "cost">; // three keys: cost dropped
type Bogus = Omit<Part, "csot">; // typo: nothing dropped, still four keys
const two: Two = { code: "BR-5", name: "bracket" };
const nocost: NoCost = { code: "WS-2", name: "washer", grade: 6 };
const bogus: Bogus = { code: "PN-9", name: "pin", grade: 9, cost: 40 };
// type Slip = Pick<Part, "csot">; // refused: 'csot' is not a key of Part
console.log(Object.keys(two).length, Object.keys(nocost).length, Object.keys(bogus).length);
Output:
2 3 4
Two has the two keys you named and NoCost the three that remain after dropping cost. Bogus is the trap: Omit<Part, "csot"> dropped nothing, because "csot" is not a key and Omit never checked, so Bogus is the full four-key Part and the object must still supply cost. The commented Pick line, by contrast, is refused outright, because Pick constrains its key to keyof Part. When you drop a field, prefer to have the key checked, and be aware that Omit will not do it for you.
ReturnType and Parameters read a function's shape
Two transformers take a function type rather than an object type. ReturnType<F> is the type the function returns; Parameters<F> is the tuple of its argument types. Both are how you name a type you did not declare, especially one buried in a third-party function.
// src/derive.ts
function issueTicket(code: string, grade: number) {
return { code, grade, issued: true };
}
type Ticket = ReturnType<typeof issueTicket>; // { code: string; grade: number; issued: boolean }
type Args = Parameters<typeof issueTicket>; // [string, number]
const t: Ticket = { code: "BR-5", grade: 7, issued: true };
const a: Args = ["WS-2", 6];
console.log(t.code, t.grade, t.issued);
console.log(a[0], a[1]);
Output:
BR-5 7 true
WS-2 6
Ticket is the inferred return shape of issueTicket, so if the function later returns another field, Ticket gains it with no edit here; Args is the argument tuple, useful for wrapping or forwarding a call. typeof issueTicket turns the value into its function type first, which is what ReturnType and Parameters consume. These are the print-room settings that trace a drawing you were handed rather than one you drew.
The transformers at a glance
The common utilities, what each produces, and whether it validates a key argument.
| Transformer | What it produces | Checks its key argument |
|---|---|---|
Partial<T> | every property optional | no key argument |
Required<T> | every property required, undefined stripped | no key argument |
Readonly<T> | every property frozen | no key argument |
Pick<T, K> | only the keys in K | yes: K must be keyof T |
Omit<T, K> | everything except the keys in K | no: K is keyof any, typos pass |
Record<K, V> | an object of K to V | yes: K fixes the key set |
ReturnType<F> | the return type of F | reads it off F |
Parameters<F> | the argument tuple of F | reads it off F |
The one row to keep in mind is Omit: it is the transformer that will not catch a mistyped key, so a slip leaves the type wider than you meant. Everything else either takes no key or checks the one it takes.
Real World Example: The Parts Catalogue
The catalogue holds one master Part type and derives every other shape from it: a Patch for updates as Partial of the editable fields, a PublicPart that Omits the internal cost, and a Summary picked down to code and grade. Deriving them means a change to Part reshapes all three, and the public table cannot accidentally name a field the master does not have.
// src/catalogue.ts
type Finish = "zinc" | "plain";
type Part = { code: string; name: string; grade: number; finish: Finish; cost: number };
type Patch = Partial<Omit<Part, "code">>; // any editable field, code fixed
type PublicPart = Omit<Part, "cost">; // the shop-floor view: no cost
type Summary = Pick<Part, "code" | "grade">; // just the grade index
type Edit = { code: string; patch: Patch };
const PARTS: readonly Part[] = [
{ code: "BR-5", name: "bracket", grade: 7, finish: "zinc", cost: 120 },
{ code: "WS-2", name: "washer", grade: 6, finish: "plain", cost: 40 },
{ code: "PN-9", name: "pin", grade: 9, finish: "plain", cost: 90 },
{ code: "CL-3", name: "clip", grade: 4, finish: "zinc", cost: 30 }
];
const EDITS: readonly Edit[] = [
{ code: "BR-5", patch: { cost: 130 } },
{ code: "PN-9", patch: { finish: "zinc" } },
{ code: "CL-3", patch: { grade: 5, cost: 35 } },
{ code: "XX-0", patch: { cost: 99 } }
];
const FINISH_ORDER: readonly Finish[] = ["zinc", "plain"];
function pad(text: string, width: number): string {
return text.length >= width ? text : text + " ".repeat(width - text.length);
}
function applyPatch(part: Part, patch: Patch): Part {
return { ...part, ...patch };
}
function toPublic(part: Part): PublicPart {
const { cost: _cost, ...rest } = part; // drop cost for the public view
return rest;
}
function run(parts: readonly Part[], edits: readonly Edit[]): string {
const current = new Map<string, Part>(parts.map((p) => [p.code, p]));
let applied = 0;
for (const edit of edits) {
const found = current.get(edit.code);
if (found === undefined) { continue; }
current.set(edit.code, applyPatch(found, edit.patch));
applied += 1;
}
const rows = parts.map((p) => current.get(p.code) ?? p);
const publicRows = rows.map(toPublic);
const summaries: Summary[] = rows.map((r) => ({ code: r.code, grade: r.grade }));
const out: string[] = [];
out.push("parts: " + String(rows.length) + ", patches applied: "
+ String(applied) + " of " + String(edits.length));
out.push(pad("CODE", 6) + pad("NAME", 9) + pad("GRADE", 7) + "FINISH");
for (const p of publicRows) {
out.push(pad(p.code, 6) + pad(p.name, 9) + pad(String(p.grade), 7) + p.finish);
}
const totalCost = rows.reduce((sum, r) => sum + r.cost, 0);
const byFinish = FINISH_ORDER
.map((fin) => [fin, publicRows.filter((p) => p.finish === fin).length] as const)
.filter(([, n]) => n > 0)
.map(([fin, n]) => fin + " x" + String(n));
const grades = summaries.map((sm) => sm.code + " " + String(sm.grade));
out.push("total cost: " + String(totalCost) + " pence (internal)");
out.push("by finish: " + byFinish.join(", "));
out.push("grades: " + grades.join(", "));
return out.join("\n");
}
console.log(run(PARTS, EDITS));
Output:
parts: 4, patches applied: 3 of 4
CODE NAME GRADE FINISH
BR-5 bracket 7 zinc
WS-2 washer 6 plain
PN-9 pin 9 zinc
CL-3 clip 5 zinc
total cost: 295 pence (internal)
by finish: zinc x3, plain x1
grades: BR-5 7, WS-2 6, PN-9 9, CL-3 5
Read the catalogue against the print room. Patch is Partial<Omit<Part, "code">>, the provisional print that lets an edit carry only the fields it changes while forbidding a change to code, so the three well-formed edits each touch one or two fields and land. PublicPart is Omit<Part, "cost">, the masked extract, and it is what the table iterates, which is why no cost column appears. Summary is Pick<Part, "code" | "grade">, the single-detail print, feeding the grades line. Every shape on the sheet is Part through one transformer.
The derived shapes track the master, and that is the point. Add a field to Part, say a supplier, and Patch can carry it, Summary ignores it, and PublicPart shows it unless you add it to the Omit list, all without editing three separate interfaces that would otherwise drift. The internal total is computed from rows, which still carry cost, while the table is built from publicRows, which do not: one master, two views, the costing block present in the arithmetic and masked in the display exactly as the print settings intend.
The program has real defects, and the sharpest sits on the public boundary. PublicPart describes a shape without cost, but nothing forces the code to use it: the boundary is held only by toPublic being called before the table is built, and a handler that serialised rows instead of publicRows would leak every cost with no type error, because rows are still full Parts. Worse, if the Omit in PublicPart were mistyped, Omit<Part, "csot">, it would silently keep cost and the leak would compile clean, the Omit gotcha turned into a data exposure. Beyond that, Patch is Partial, so it can set a field but never clear one; the dropped XX-0 edit is reported only as the bare "3 of 4" with no note of which code missed; and the internal total, though labelled, prints in the same stream as the public table, so anything reading that output sees the figure the PublicPart type went to trouble to hide.
Common Mistakes
- Hand-writing a second interface instead of deriving it: a separate
UserUpdatebesideUserdrifts the moment one changes;Partial<Pick<User, ...>>stays tied to the master. - Trusting
Omitto catch a mistyped key:Omit<Part, "csot">drops nothing and returns the full type, because its key parameter iskeyof any; verify the key or use a checked alternative. - Believing
Required<Partial<T>>restoresTexactly: it restores the keys as required but stripsundefinedfrom their types, so a property typedstring | undefinedcomes back plainstring. - Reaching for
Partial<T>as a function parameter and then not handling the gaps: every field is now possiblyundefined, so the body must default or guard each one it reads. - Assuming a
PublicPart-style type enforces the boundary: the type only describes the shape; unless the code actually maps through it, the fuller object still flows out untouched. - Using
PickorOmitwith a runtime value: they are type-level only and erase at compile time; to drop a key at runtime you still needdeleteor a destructure. - Deriving from a derived type in a long chain:
Partial<Omit<Pick<T, ...>, ...>>is legal but unreadable; name the intermediate steps or reconsider the master. - Forgetting that
Readonly<T>is shallow: it freezes the top-level properties only, so a nested object or array inside aReadonlytype is still mutable. - Passing a mutable object where a
Readonly<T>was expected and back again: the read-only view shares the same object, so mutating the original still changes what the read-only reference sees.
Best Practices
- Keep one master type and derive every view from it:
Partial,Pick,OmitandReadonlyslice a single source of truth so the views cannot drift apart. - Prefer
PickoverOmitwhen you can name what to keep:Pickchecks its keys againstkeyof T, so a typo is caught, whereOmitlets it pass. - Use
Partial<T>for update payloads andRequired<T>for validated records: the pair expresses "some fields" and "all fields" from the one type. - Reach for
ReturnTypeandParametersto name a function's shape: it ties your type to the function's actual signature instead of a hand-copied duplicate that rots. - Map through the narrower type at the boundary, do not just annotate it: build
publicRowswith atoPublicand return those, so the fuller object cannot leak. - Name intermediate derived types rather than nesting transformers deeply:
type Editable = Omit<Part, "code">thenPartial<Editable>reads where a triple-nested one-liner does not. - Remember
Readonlyand the mapped utilities are shallow: reach for a recursiveDeepReadonlyorObject.freezeper level when you need depth. - Treat utility types as compile-time only: to change a value at runtime you still write the code; the transformer only shapes the type.
Practice Exercises
- The Update Payload: Given
interface Account { id: number; email: string; plan: string }, derive anAccountUpdatethat allows changingemailandplanbut neverid, usingPartialandOmit(orPick), and build one valid update. - The Omit Trap: Write
Omit<Account, "eamil">with the typo, construct a value of it, and show by counting keys that nothing was dropped; then rewrite it so the compiler would have caught the mistake. - The Function Shape: Write a function
makeToken(user: string, ttl: number)returning an object, then derive its return type withReturnType<typeof makeToken>and its argument tuple withParameters, and build a value of each. - The Enforced Boundary: Take
catalogue.ts, add a route that returns the rows as JSON, show that returningrowsleakscost, then fix it by returningpublicRowsand explain why thePublicParttype alone did not prevent the leak.