Array Mapping and Transformation Generics
What you'll learn: How TypeScript's array methods like map, filter, and reduce use generics to preserve type information through transformations.
The Type-Safe Transformation Pipeline
When you transform an array in JavaScript, the output type often differs from the input type. Without generics, you'd lose track of what you're working with. TypeScript's built-in array methods use generics to maintain type safety at every step.
Think of it like a factory assembly line: raw materials go in one end, finished products come out the other. Generics ensure you always know what's on the conveyor belt at each stage.
How map, filter, and reduce Use Generics
Array<T>.map<U> transforms T[] into U[]:
const numbers: number[] = [1, 2, 3];
const strings: string[] = numbers.map(n => n.toString());
// TypeScript infers: map<string>
Array<T>.filter narrows or maintains T[]:
const mixed: (number | null)[] = [1, null, 3];
const onlyNumbers: (number | null)[] = mixed.filter(x => x !== null);
// Still (number | null)[] without a type predicate
Array<T>.reduce<U> accumulates from T[] into U:
const words: string[] = ["hello", "world"];
const lengths: number = words.reduce((sum, word) => sum + word.length, 0);
// TypeScript infers: reduce<number>
Why This Matters
These transformations happen constantly in real code. Generics ensure that when you transform User[] into UserId[], TypeScript knows you're working with user IDs afterward—no type information lost, no manual annotations needed (usually).
Key Takeaway: Array transformation methods use generics to maintain type safety through the entire pipeline, inferring output types from your transformation logic automatically.