Array Manipulation with Generics
You'll learn how to write generic versions of common array operations that preserve the types of elements flowing through your functions.
The Core Idea
When you build functions like map, filter, or reduce from scratch, generics let you maintain type safety end-to-end. Instead of accepting any[] and returning any[] (losing all type information), you use type parameters to capture what goes in and guarantee what comes out matches your transformation logic.
Why This Matters
Imagine writing a custom map function without generics:
function mapBad(arr: any[], fn: (x: any) => any): any[] {
const result = [];
for (const item of arr) {
result.push(fn(item));
}
return result;
}
This works at runtime but destroys type safety. TypeScript can't tell you what's in the result array.
Generic Array Mapping
With generics, you preserve input and output types:
function map<T, U>(arr: T[], fn: (item: T) => U): U[] {
const result: U[] = [];
for (const item of arr) {
result.push(fn(item));
}
return result;
}
const numbers = [1, 2, 3];
const strings = map(numbers, n => n.toString()); // string[]
Type parameter T represents the input array's element type, while U represents what your transformation produces. TypeScript infers both automatically.
Generic Filtering
function filter<T>(arr: T[], predicate: (item: T) => boolean): T[] {
const result: T[] = [];
for (const item of arr) {
if (predicate(item)) {
result.push(item);
}
}
return result;
}
const evens = filter([1, 2, 3, 4], n => n % 2 === 0); // number[]
Key Takeaway: Generic array manipulation functions use type parameters to track element types through transformations, ensuring the output type correctly reflects your operation's logic without sacrificing type safety.