Mapped Types: The Factory Line

Mapped Types: The Factory Line in TypeScript: A steel finishing works runs a galvanizing line: a jig of raw steel parts is hung on hooks, wheeled through a…

The Analogy: The Galvanizing Line at a Steel Finishing Works

A steel finishing works runs a galvanizing line: a jig of raw steel parts is hung on hooks, wheeled through a bath of molten zinc, and emerges at the far end with every part carrying a zinc coat. What comes out is not a different set of parts. It is the same parts, on the same hooks, in the same positions, each one now transformed by the identical treatment. That is exactly what a mapped type does to a type: it takes an existing set of keyed properties and produces a new type with the same keys, each value put through the same transformation.

The jig is the important detail, because the jig decides which hooks exist. You cannot coat a part that was never hung, and every part that is hung goes through the bath. In a mapped type the jig is keyof T: the keys of the new type come from the source type, no more and no fewer, and the loop [K in keyof T] visits each one in turn. The treatment itself can be an addition, such as sealing every part with a protective wax that fixes it in place, which is how the readonly and optional modifiers get added; or it can be the reverse, a stripping bath that removes a coat the parts arrived with, which is how the minus modifiers take a coat back off.

Not every line coats every part identically. A masking station can pull selected parts off the line before the bath, so only the qualifying parts carry on, and a re-hanging station can move parts onto differently labelled hooks. That is key remapping with the as clause: a key can be sent to nowhere and dropped from the result, or given a new name. Contrast this with a fixed-recipe dip tank that coats a preset checklist of parts regardless of what any incoming jig held; that is Record, which begins from a supplied list of names rather than transforming an existing part set, and so it does not carry any modifiers across because there was no source jig to carry them from.

The line's power and its hazard are the same fact: it treats every part on the jig identically. If one part must stay bare, a machined mating face or a threaded insert that zinc would foul, a blanket coat quietly ruins the one part that needed an exception, and the only defence is for the operator to mask it off deliberately, which is to say to filter that key out before the transform. Worse, the line records only the finish and not the reasons, so a masked-off part is simply absent at the end with no note explaining the gap. A homogeneous transform assumes homogeneity, and the moment the parts are not uniform you must encode the exceptions explicitly or you get uniform wrongness applied with perfect consistency.


Syntax or Core Structure

A mapped type walks the keys of an existing type with [K in keyof T] and produces a new property for each. The value type on the right can reuse T[K], the type of the original property, or wrap it in something new. This example keeps every key but transforms each value into a small record that pairs the original value with a coated flag.

// src/coat.ts
interface Part {
    bracket: number;
    bolt: number;
    washer: number;
}

// Same keys as Part, each value wrapped
type Coated<T> = {
    [K in keyof T]: { raw: T[K]; coated: boolean };
};

function coat(part: Part): Coated<Part> {
    return {
        bracket: { raw: part.bracket, coated: true },
        bolt: { raw: part.bolt, coated: true },
        washer: { raw: part.washer, coated: true },
    };
}

const out = coat({ bracket: 3, bolt: 8, washer: 5 });
console.log(out.bracket.raw + " " + out.bracket.coated);
console.log(out.bolt.raw + " " + out.bolt.coated);
console.log(out.washer.raw + " " + out.washer.coated);
console.log("total " + (out.bracket.raw + out.bolt.raw + out.washer.raw));

Output:

3 true
8 true
5 true
total 16

The type Coated<Part> has exactly the keys bracket, bolt, and washer, because those are the keys keyof Part produced, and each value is now a { raw: number; coated: boolean } record rather than a bare number. The runtime value mirrors the type: every part is rebuilt with its original number under raw and coated: true alongside. Reading the three raw values back gives 3, 8, and 5, which sum to 16. The keys came from the source type and the transformation was applied uniformly to each, which is the whole shape of a mapped type.


Technical Depth: Modifiers, Filters, and Record

The value transform is only half of what a mapped type can do. The other half is the modifiers on the property itself: whether it is optional, and whether it is readonly. A mapped type can add these, and, less well known, it can strip them off with a minus sign.

Adding and removing modifiers

Placing ? after the key clause makes every property optional, which is exactly how the built-in Partial is defined. This is the sealing bath: every part comes out optional.

// src/partial.ts
interface Box {
    width: number;
    height: number;
}

// Every property optional -- this is how Partial<T> is written
type MyPartial<T> = {
    [K in keyof T]?: T[K];
};

function area(box: MyPartial<Box>): number {
    const w = box.width ?? 0;
    const h = box.height ?? 0;
    return w * h;
}

console.log(area({ width: 4, height: 5 }));
console.log(area({ width: 4 }));
console.log(area({}));

Output:

20
0
0

Because MyPartial<Box> makes both width and height optional, area must cope with either being absent, which is why each is defaulted to 0 with ??. The first call has both, giving 4 * 5 = 20; the second is missing height, so 4 * 0 = 0; the third is the empty object, giving 0 * 0 = 0. The reverse operation strips the optional coat back off with -?, which is how Required is defined:

// src/required.ts
interface Draft {
    title?: string;
    pages?: number;
}

// Remove the optional modifier from every property
type MyRequired<T> = {
    [K in keyof T]-?: T[K];
};

function describe(book: MyRequired<Draft>): string {
    return book.title + " (" + book.pages + ")";
}

console.log(describe({ title: "Atlas", pages: 120 }));
console.log(describe({ title: "Index", pages: 44 }));

Output:

Atlas (120)
Index (44)

In MyRequired<Draft>, the -? removes the optional coat the Draft properties arrived with, so title and pages are now mandatory and describe can read them without a guard. The same trick with -readonly produces a Mutable<T>. The minus modifiers only make sense on a homomorphic mapped type, one written over keyof T, because there has to be an existing coat to take off.

Filtering keys by remapping to never

The masking station pulls parts off the line before the bath. In a mapped type that is the as clause: remap a key to never and it vanishes from the result entirely. Combined with a check on the value type, this keeps only the properties you want.

// src/filter.ts
interface Row {
    sku: string;
    qty: number;
    price: number;
    active: boolean;
}

// Keep only the keys whose value is a number; drop the rest
type NumbersOnly<T> = {
    [K in keyof T as T[K] extends number ? K : never]: T[K];
};

function total(row: NumbersOnly<Row>): number {
    return row.qty + row.price;
}

console.log(total({ qty: 6, price: 40 }));

Output:

46

NumbersOnly<Row> is { qty: number; price: number }. The as clause sends each key either to itself, when its value is a number, or to never, when it is not, and a key mapped to never is dropped, so sku and active disappear. total therefore accepts only the two numeric fields and returns 6 + 40 = 46. Renaming a key to something new rather than dropping it needs template literal types, which are their own topic; here the as clause is used purely to filter.

Homomorphic mapped types versus Record

A mapped type written over keyof T is called homomorphic: it mirrors an existing shape and carries that shape's modifiers across. Record is the other kind, built from a supplied union of key names rather than from an existing type, so there is no source shape and no modifiers to carry.

AspectHomomorphic over keyof TRecord of a key union
Key sourcean existing type's keysa supplied union of names
Modifiers carriedreadonly and optional preservednone to carry across
Typical usereshape a known typebuild a fresh lookup table
Built-in examplesPartial, Readonly, PickRecord
// src/record.ts
type Colour = "red" | "amber" | "green";

// Record builds a fresh lookup keyed by the union members
type Tally = Record<Colour, number>;

const counts: Tally = { red: 2, amber: 3, green: 7 };

let total = 0;
const order: Colour[] = ["red", "amber", "green"];
for (const key of order) {
    total += counts[key];
}
console.log("colours " + order.length);
console.log("total " + total);

Output:

colours 3
total 12

Record<Colour, number> requires every member of the Colour union to be present with a number value, so the compiler would reject a counts object that forgot green. Iterating an explicit ordered array rather than Object.keys keeps the sum deterministic, giving 2 + 3 + 7 = 12 across the three colours. Note that Record starts from the key union outward, whereas Partial and the filter above start from an existing type inward: that direction is the whole difference between the two families.


Real World Example: One Product Type, Three Derived Shapes

A catalogue has a single canonical Product type, and several other shapes are needed around it: a patch shape where every field is optional so a partial update can be applied, and a validation shape where every field is replaced by a boolean saying whether it passed. Rather than hand-writing three parallel types that will drift apart, both derived shapes are mapped types over Product, so the source stays the single point of truth and any new field automatically flows into all three.

// src/catalogue.ts
interface Product {
    sku: string;
    price: number;
    stock: number;
}

// Every field optional: a partial update
type Patch<T> = {
    [K in keyof T]?: T[K];
};

// Every field replaced by a pass/fail flag
type Flags<T> = {
    [K in keyof T]: boolean;
};

function applyPatch(base: Product, patch: Patch<Product>): Product {
    return {
        sku: patch.sku ?? base.sku,
        price: patch.price ?? base.price,
        stock: patch.stock ?? base.stock,
    };
}

function validate(product: Product): Flags<Product> {
    return {
        sku: product.sku.length > 0,
        price: product.price > 0,
        stock: product.stock > 0,
    };
}

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

const base: Product = { sku: "AX1", price: 40, stock: 5 };
const updated = applyPatch(base, { price: 55, stock: 0 });
const flags = validate(updated);

console.log("sku " + updated.sku);
console.log("price " + updated.price);
console.log("stock " + updated.stock);

let passed = 0;
const order: (keyof Product)[] = ["sku", "price", "stock"];
console.log(pad("FIELD", 8) + "VALID");
for (const key of order) {
    if (flags[key]) {
        passed++;
    }
    console.log(pad(key, 8) + flags[key]);
}
console.log("passed " + passed + "/" + order.length);

Output:

sku AX1
price 55
stock 0
FIELD   VALID
sku     true
price   true
stock   false
passed 2/3

Trace it through. The patch sets price to 55 and stock to 0, leaving sku absent. In applyPatch the ?? operator keeps the base value only when the patch field is null or undefined, so sku falls back to "AX1", price becomes 55, and stock becomes 0 (crucially, 0 is kept, not treated as missing). Validation then checks each field: sku is non-empty so true, price is above zero so true, but stock is exactly zero so false. Two of the three fields pass, giving passed 2/3.

The value of the mapped-type approach is that Patch<Product> and Flags<Product> are generated from Product, not maintained beside it. Add a weight field to Product and the patch shape gains an optional weight and the flags shape gains a weight: boolean with no further edits, and applyPatch and validate will fail to compile until they handle it, which is precisely the reminder you want. The two derived types cannot silently fall out of step with the source.

That very uniformity is also the design's flaw, and it is worth naming honestly. Patch<Product> makes every field optional including sku, but it also permits sku: "", and because applyPatch guards only against null and undefined with ??, a patch carrying an empty string would blank a required field while passing every type check; a real patch type would need a tighter value type or a validation step that a blanket mapped type cannot express. Two smaller limits sit alongside: Flags<Product> collapses each field to a bare boolean and so throws away any reason for a failure, where a UI would want the message too; and the stock: 0 case only survives because applyPatch uses ?? rather than ||, a distinction the mapped type itself does nothing to enforce and that a careless edit could quietly break.


Common Mistakes

  1. Forgetting that mapped types are erased at runtime. They describe shapes for the compiler only; a Readonly<T> value can still be mutated at runtime unless you also Object.freeze it.
  2. Writing the key clause as [K in T] instead of [K in keyof T]. The loop must range over the keys of T, so keyof is required unless T is already a union of keys.
  3. Expecting Readonly or Partial to be deep. Both are shallow: nested objects keep their original, mutable, required shape, so a deep transform needs a recursive mapped type.
  4. Hand-rolling a utility that already exists. Partial, Required, Readonly, Pick, Record, and Omit are built in; reinvent them only to learn how they work, not in production.
  5. Adding -? or -readonly to a non-homomorphic mapped type. The minus modifiers only remove a coat the source had, so they are meaningful only on a mapping written over keyof T.
  6. Mapping a key to never by accident. An as clause whose every branch resolves to never silently drops all keys and leaves you with an empty object type.
  7. Trying to rename keys without template literal types. The as clause can filter with never, but constructing a new key name such as a get-prefixed accessor needs a template literal type.
  8. Confusing Record with a homomorphic mapping. Record builds from a supplied key union and carries no modifiers across, so it cannot preserve a source type's readonly or optional flags.
  9. Assuming Partial makes a value safe to read. Optional means possibly undefined, so every field of a Partial<T> still needs a guard or a default before use.

Best Practices

  • Reach for the built-in utility types first. Partial, Required, Readonly, Pick, Omit, and Record cover most needs and are instantly recognisable to other readers.
  • Write custom mapped types over keyof T when you want modifiers preserved. A homomorphic mapping keeps the source's readonly and optional coats, which is usually what you intend.
  • Filter keys with an as ... : never clause. Remapping unwanted keys to never is the idiomatic way to drop properties from the result.
  • Pair Readonly<T> with Object.freeze when you need runtime immutability. The type alone is a compile-time promise, not a runtime guard.
  • Name a derived mapped type for its intent, not its mechanism. Patch and Flags read better than PartialProduct or BooleanProduct.
  • Derive related shapes from one canonical type. Generating a patch and a validation shape from the source keeps them in step and turns a new field into a compile error until every derived user handles it.
  • Keep the value transform simple. If the right-hand side of a mapped type grows a large conditional, a named helper type or a rethink usually reads better than one dense expression.
  • Iterate derived records over an explicit key list. When you must loop a mapped or Record type at runtime, a typed (keyof T)[] array keeps both the order and the exhaustiveness under your control.

Practice Exercises

  1. The Freezer. Write AllReadonly<T> that marks every property readonly, apply it to a two-field interface, and confirm the compiler rejects an assignment to one of the fields.
  2. The Thaw. Write Mutable<T> using -readonly that strips the readonly modifier from every property, and prove it by reassigning a field that was read-only on the source type.
  3. The Sieve. Write StringsOnly<T> that keeps only the properties whose value type is string, using an as ... : never clause, and check the resulting type has dropped every non-string key.
  4. The Twin Shapes. Given one Order interface, derive both a Patch<Order> and a Flags<Order>, then add a new field to Order and confirm both derived shapes and the functions that consume them force you to handle it.