[K in keyof T] Mapped Types
Last updated: 2026-10-22
[K in keyof T] Mapped Types
A mapped type walks keys and transforms values: [K in keyof T]: boolean generates a same-named property for every key K of T. It is the assembly line for batch type changes — Partial's optionality and Readonly's immutability are both one-line mappings.
| Group | Generics |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
type BooleanFlags<T> = {
[K in keyof T]: boolean;
};
// Modifier combos: readonly adds immutability, -? strips optionality
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type Concrete<T> = { [K in keyof T]-?: T[K] };
⚙️ Parameters
| [K in keyof T] | The iteration clause: K binds each of T's keys in turn |
|---|---|
| T[K] | The value transform: the new property's type, freely computed (boolean, T[K] | null, wrappers, ...) |
| readonly / ? / -? | Modifiers: readonly and optionality may be added or removed during mapping |
Returns:A mapped type produces a new object type: same keys as T (or filtered/renamed via as), with value types transformed by the rule.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
{"dark":true,"beta":false,"newNav":true}
true false
(Runtime output after transpilation; flags.dark is boolean, not the literal true — the mapping turned every field into boolean)
💡 Notes
ℹ️ Info The built-ins Partial, Readonly, Pick and Record are all mapped types — understand [K in keyof T] and half the utility-type chapter is readable.
💡 Tip The as clause renames or filters keys: { [K in keyof T as NewKey<K>]: T[K] } renames via template literals, as never deletes the key — advanced key-and-value reshaping.
⚠️ Note Mapping over keyof T is homomorphic (modifiers preserved), but mapping over a plain union (Record-style) drops optional/readonly — the usual answer to "where did my ? go?".
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Mapped type vs index signature?
A An index signature [k: string]: T says "every key is T" with unbound keys; a mapping [K in keyof T] copies known keys one by one with per-key precision. Broad fallback vs exact transformation.
Q Can you map only some keys?
A Yes: filter with as ([K in keyof T as K extends "id" ? never : K]) or Pick/Omit before mapping. Key-set trimming happens in the as clause.
Q Can mapped types produce functions or arrays?
A Yes: { [K in keyof T]: (v: T[K]) => void } yields a set of callbacks; { [K in keyof T]: T[K][] } arrays every field — value transforms are not limited to simple types.