TypeScript theorytheory 0/50 · 0%
Collections · easy

15. Working with arrays: map/filter/reduce, typed

Typed transformations over collections.

Array methods keep full type information through transformations. `map` can change the element type; `filter` narrows when given a type predicate; `reduce` needs an explicit accumulator type when it's not obvious.

ts
interface Tx { hash: string; value: number; }

const txs: Tx[] = [{ hash: "0x1", value: 5 }, { hash: "0x2", value: 0 }];

const hashes: string[] = txs.map(t => t.hash);
const nonZero: Tx[] = txs.filter(t => t.value > 0);
const total: number = txs.reduce((sum, t) => sum + t.value, 0);

A type predicate function like `(t: Tx): t is Tx => ...` lets `filter` narrow a union array, e.g. removing `undefined` entries from `(Tx | undefined)[]` and returning a properly typed `Tx[]`.

Check your understanding

  1. 1. What does `.map` do to the type of an array?

  2. 2. What is needed for `.filter` to narrow a union array type?

  3. 3. In `reduce((sum, t) => sum + t.value, 0)`, what does the `0` do besides being the initial value?