Array Methods with Types

map, filter, and reduce keep their types so you get autocomplete and safety.

Syntaxarr.map(x => x * 2)

All the familiar array methods work in TypeScript, and the types flow through automatically.

  • map transforms each element into a new one.
  • filter keeps elements that match a condition.
  • reduce combines everything into a single value.

Because TypeScript knows the element type, it knows what methods are available on each item inside the callback.

Example

Try it yourself
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.

Example · ts
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.

Example · ts
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.

Example · ts
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

  • Be the first to comment on this lesson.