Course contentsShow
← TypeScript
Lesson 1738 of 1,79639. TypeScript PerformanceFree lesson

Cache Expensive Mapped Type Results

Store the result of complex mapped types in a type alias to prevent recalculation on every usage.

Cache Expensive Mapped Type Results

What you'll learn: How to store complex mapped type computations in type aliases to avoid recalculating them on every usage, improving TypeScript's compilation performance.

The Performance Problem

When you write a mapped type inline, TypeScript recalculates it every single time it's used. If that mapped type is complex—iterating over many keys, applying conditional logic, or performing string template manipulations—the compiler does redundant work at every call site.

Think of it like recomputing a complex mathematical formula every time you need the answer, instead of calculating once and saving the result.

The Solution: Cache in Type Aliases

Extract expensive mapped types into named type aliases. TypeScript can then reference the cached result instead of re-executing the transformation:

// ❌ BAD: Recalculated every time
function transform<T extends object>(obj: T): {
  [K in keyof T]: T[K] extends string ? number : T[K]
} {
  // implementation
}

// ✅ GOOD: Calculated once, reused
type TransformStringsToNumbers<T> = {
  [K in keyof T]: T[K] extends string ? number : T[K]
};

function transform<T extends object>(obj: T): TransformStringsToNumbers<T> {
  // implementation
}

When This Matters Most

The performance win becomes significant with:

  • Large object types with dozens of properties
  • Complex transformations using conditionals and nested mapped types
  • High-frequency usage in heavily-used utility functions
  • String template literal types which are expensive to process

Real-World Pattern

// Cache complex transformation
type DeepReadonlyFields<T> = {
  readonly [K in keyof T]: T[K] extends object 
    ? DeepReadonlyFields<T[K]> 
    : T[K]
};

// Reuse the cached type
function freeze<T>(obj: T): DeepReadonlyFields<T> {
  return obj;
}

const config = freeze({ api: { url: "..." } });
// Type checking reuses cached DeepReadonlyFields

Key Takeaway: Store the results of complex mapped types in type aliases rather than repeating them inline—your compiler (and your build times) will thank you.