Advertisement
Advanced TypeScript, Mapped Types

How do homomorphic mapped types (those that map directly over `keyof T` for a generic T) preserve extra information like optionality, compared to non-homomorphic ones?

Short answer

A homomorphic mapped type — one written as `{ [K in keyof T]: ... }` directly over a generic T — automatically preserves T's original modifiers (optional, readonly) and array/tuple structure unless explicitly overridden with +/-.

Save TypeScript mock interview
Advertisement
AModel answer
A homomorphic mapped type — one written as `{ [K in keyof T]: ... }` directly over a generic T — automatically preserves T's original modifiers (optional, readonly) and array/tuple structure unless explicitly overridden with +/-. A non-homomorphic mapped type (iterating over a fixed union of string literals instead of `keyof T`) does NOT get this automatic preservation, since there's no single source type to copy modifiers from.
// Homomorphic: preserves Person's original optional/readonly modifiers automatically
type Copy<T> = { [K in keyof T]: T[K] };

// Non-homomorphic: modifiers aren't inherited from any single source type
type FixedKeys = { [K in 'a' | 'b']: string };
Real-world example
Understanding why some custom mapped-type utilities unexpectedly preserve readonly/optional modifiers while others don't.
Likely follow-ups
  • How does this distinction affect a mapped type applied to a tuple or array type specifically?
Related topics