Homomorphic vs Non-Homomorphic Mapped Types
You'll learn: Why certain mapped types compile dramatically faster than others, and how TypeScript treats modifier-preserving transformations differently under the hood.
What Are Homomorphic Mapped Types?
When TypeScript encounters a mapped type that preserves the structure and modifiers of the original type (like readonly and ?), it can use a special optimization path. These are called homomorphic mapped types — they maintain the "shape" of the input type.
The key: mapping over keyof T directly signals to TypeScript that you're transforming an existing type while preserving its modifiers.
// Homomorphic - preserves readonly, optional modifiers
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type MyReadonly<T> = {
[K in keyof T]: T[K];
};
These look like they're just iterating keys, but TypeScript recognizes the pattern [K in keyof T] and treats it specially.
Non-Homomorphic Mapped Types
When you map over a union of keys that didn't come from keyof T, or when you explicitly override modifiers, TypeScript must perform full type expansion:
// Non-homomorphic - maps over explicit union, not keyof T
type Record<K extends string, V> = {
[P in K]: V;
};
// Non-homomorphic - explicitly adds modifiers
type ForceReadonly<T> = {
+readonly [K in keyof T]: T[K];
};
The Record utility maps over arbitrary K, not the structure of an existing type. TypeScript can't use the homomorphic optimization.
The Performance Difference
Homomorphic mapped types:
- Preserve existing modifiers automatically
- TypeScript reuses internal type structure
- Faster to check and instantiate
- Built-in utilities like
Partial,Readonly,Pickuse this
Non-homomorphic mapped types:
- Must construct entirely new type structure
- Each property's modifiers are recalculated
- Slower with large object types
- Still correct, just more expensive
Think of homomorphic types as copying with modifications (efficient), while non-homomorphic types rebuild from scratch (thorough but slower).
When It Matters
The performance gap becomes noticeable with:
- Very large object types (100+ properties)
- Deeply nested mapped type chains
- Heavy type inference contexts
- Large codebases with many type instantiations
For most everyday types, the difference is negligible. But library authors and complex generic utilities benefit from understanding which pattern triggers which path.
Key Takeaway: Homomorphic mapped types ([K in keyof T]) preserve modifiers and compile faster than non-homomorphic types that map over explicit key unions or force modifier changes, because TypeScript can optimize structure-preserving transformations.