The Array.map Example
You'll learn why Array.map needs generics to preserve type information through transformations.
The Problem Without Generics
When you call .map() on an array, you're transforming each element into something potentially different. The output type depends entirely on what your callback returns, not on what went in.
If map were typed with a union of all possible return types, it would lose precision completely. Imagine:
const numbers = [1, 2, 3];
const strings = numbers.map(n => n.toString());
Without generics, TypeScript would have no way to know that strings is string[]. It might widen to (number | string | boolean | ...)[] — essentially useless.
How Generics Solve This
The actual signature of Array.map looks roughly like:
map<U>(callbackfn: (value: T) => U): U[]
Here, T is the array element type (already known from the array itself), and U is inferred from what the callback returns.
const numbers = [1, 2, 3];
// U is inferred as string because callback returns string
const strings = numbers.map(n => n.toString()); // string[]
// U is inferred as boolean because callback returns boolean
const flags = numbers.map(n => n > 2); // boolean[]
The generic U flows through from the callback's return type to the resulting array type. This wouldn't be possible with a fixed union — every callback produces its own specific output type.
Why Not a Union?
A union would mean: "map returns an array of one of these types." But that's not what happens. Map returns an array of exactly the type your callback produces, which varies per usage.
Key Takeaway: Array.map uses generics because the output type is determined dynamically by the callback's return type, not a static set of possibilities — this is type preservation, not type selection.