Course contentsShow
← TypeScript
Lesson 598 of 1,79614. Generics in PracticeFree lesson

Generic Cache and Memoization

Type caching utilities that preserve input-output type relationships for arbitrary functions.

Generic Cache and Memoization

What You'll Learn

You'll learn how to build type-safe caching utilities that preserve the exact input-output type relationships of any function you memoize.


What Is Generic Cache and Memoization?

Memoization is the pattern of caching a function's results so repeated calls with the same arguments return cached values instead of recomputing. Generic cache utilities use type parameters to capture the exact signature of the function being cached—ensuring TypeScript knows what arguments are valid and what type the result will be.

Without generics, a cache might accept any function and return any result, losing all type safety. With generics, you preserve the contract: if you memoize a (name: string) => number function, TypeScript still enforces that you must pass a string and will receive a number.


The Pattern

Think of a generic memoization function as a "wrapper factory": you hand it any function, and it gives you back a function with the same signature that happens to cache results internally. The type parameter T captures the original function type, and the return type is also T—meaning input types and output type flow through unchanged.

type Fn = (...args: any[]) => any;

function memoize<T extends Fn>(fn: T): T {
  const cache = new Map<string, ReturnType<T>>();
  
  return ((...args: Parameters<T>): ReturnType<T> => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key)!;
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  }) as T;
}

Here, Parameters<T> and ReturnType<T> extract the parameter and return types from the generic function type T, ensuring the cached wrapper has the exact same signature.


Key Takeaway:
Generic cache and memoization utilities use constraints and utility types to preserve the input-output contract of any function, giving you reusable caching that stays fully type-safe across different function signatures.