Generic Memoization and Caching
What you'll learn: How to build type-safe memoization and caching functions that automatically preserve the relationship between inputs and outputs.
Memoization is a technique where you cache the result of expensive function calls and return the cached result when the same inputs occur again. Without generics, you'd lose type information — your cache would store any values, and you'd have no guarantee the return type matches the input.
The Core Problem
Imagine caching a function's results. You need the cache to:
- Accept any function with any parameter types
- Return a new function with the exact same signature
- Store and retrieve values based on input arguments
Generics let you capture these relationships precisely.
A Simple Memoization Example
function memoize<T extends unknown[], R>(
fn: (...args: T) => R
): (...args: T) => R {
const cache = new Map<string, R>();
return (...args: T): R => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key)!;
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// TypeScript knows add returns number
const add = (a: number, b: number): number => a + b;
const memoizedAdd = memoize(add);
const result = memoizedAdd(2, 3); // number, not any
Here, T extends unknown[] captures the parameter types as a tuple, and R captures the return type. The memoized function maintains the exact same type signature as the original.
Why This Matters
Without generics, you'd lose autocomplete, type checking on arguments, and return type safety. With them, your cached functions behave identically to the originals from TypeScript's perspective — the cache is completely transparent.
Key Takeaway: Generic memoization captures function signatures (T for parameters, R for return type) to create type-safe caches that preserve input/output relationships while staying completely invisible to TypeScript's type system.