advanced · 23 minute study
Derive contracts without copying fields
Copied DTOs drift. Mapped types and utility types derive related shapes while making their limitations visible.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Generics preserve relationships — A reusable function should preserve what it knows about the caller's data instead of returning any or a vague union.
First, build a mental model
A mapped type is a loop over property keys that constructs a new contract. It transforms types, not the runtime object.
- keyof gives the keys to iterate.
- T[K] reuses each property's type.
- Optional/readonly modifiers change the resulting contract.
- Pick/Omit are type projections; build a corresponding runtime projection before publishing data.
type Item = { id: string; title: string; stock: number };
type Flags<T> = { [K in keyof T]: boolean };
type ItemFlags = Flags<Item>;
type ItemPatch = Partial<Pick<Item, 'title' | 'stock'>>;
const patch: ItemPatch = { stock: 4 };
type RequiredFields<T> = { [K in keyof T]-?: T[K] };- Keys
Flags visits id, title and stock.
- Map
Each output property becomes boolean.
- Patch
Only title and stock may be patched; either can be omitted.
Production thinking
Take this beyond the example.
Use mapped utilities to reduce drift, but keep public contracts intentionally small. A convenient patch type is not a field-level authorization policy.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Conditional types are type-level decisions →