BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🗺️

Mapped Types: One Rule, Every Property

💡 A mapped type iterates a type's keys with [K in keyof T] and rewrites every property by a single uniform rule.

Recall from the keyof card that keyof T gives you a union of a type's property names. A mapped type puts that union to work: it walks over every key and builds a new type by transforming each property with a single rule. The syntax is { [K in Keys]: Transform } — read it as "for each key K in Keys, create a property whose type is Transform."

Here's the classic example — make every property optional:

ts
type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

type User = { id: number; name: string };
type Draft = MyPartial<User>;
// { id?: number; name?: string }

The [K in keyof T] iterates the keys, T[K] is an indexed access that looks up each property's original type, and the ? is a modifier applied uniformly. This is exactly how the built-in Partial works.

Modifiers are the real power. You can add or strip ? (optionality) and readonly using the +/- prefixes. Readonly adds readonly to every key; Required uses -? to remove optionality. You can also remap the value type entirely — { [K in keyof T]: boolean } turns any object into a set of flags. One rule, applied to the whole shape.

🗺️ Mapped Types: One Rule, Every Property — BeCuriouz