Array Methods with Types
map, filter, and reduce keep their types so you get autocomplete and safety.
Syntax
arr.map(x => x * 2)All the familiar array methods work in TypeScript, and the types flow through automatically.
maptransforms each element into a new one.filterkeeps elements that match a condition.reducecombines everything into a single value.
Because TypeScript knows the element type, it knows what methods are available on each item inside the callback.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A dashboard filters a User[] array to only active users, and TypeScript preserves the User[] return type from filter.
- A reporting tool uses reduce on a number[] to sum invoices, with the accumulator typed as number throughout.
- A UI list uses map on a Product[] to extract names, and the result is correctly inferred as string[].
More examples
map preserves element type
Shows that map infers the output array type from the callback return type, producing number[] or string[] automatically.
const prices: number[] = [10.5, 20.0, 5.75];
const withTax: number[] = prices.map((p) => p * 1.2);
const labels: string[] = prices.map((p) => `$${p.toFixed(2)}`);filter narrows typed arrays
Filters an array of typed objects and TypeScript retains the User[] type on the result.
interface User {
name: string;
active: boolean;
}
const users: User[] = [
{ name: 'Alice', active: true },
{ name: 'Bob', active: false },
];
const activeUsers: User[] = users.filter((u) => u.active);reduce with typed accumulator
Demonstrates reduce with an explicit type argument to define the accumulator shape, including a non-trivial object accumulator.
const amounts: number[] = [100, 250, 75];
const total: number = amounts.reduce<number>((acc, n) => acc + n, 0);
const grouped = amounts.reduce<Record<string, number>>(
(acc, n) => ({ ...acc, [n]: n * 1.1 }),
{}
);
Discussion