AnyCompiler

Array Methods: map, filter, and reduce

map() and filter() work exactly like in JavaScript, but TypeScript tracks the type through the transformation — map a number[] with a function that returns a string, and the result is inferred as string[], with no annotation needed.

const numbers: number[] = [1, 2, 3, 4, 5];
const squared = numbers.map((x) => x * x);
console.log(squared);

const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens);
Output
[ 1, 4, 9, 16, 25 ]
[ 2, 4 ]

reduce — combining every item into one value

reduce() carries an accumulator forward from one item to the next. TypeScript infers the accumulator's type from the starting value you provide.

const numbers: number[] = [1, 2, 3, 4, 5];
const total = numbers.reduce((sum, x) => sum + x, 0);
console.log(total);
Output
15

Next: exception handling — catching errors, and why a caught error is typed unknown, not any.

Practice exercise

Given prices: number[] = [10, 20, 30], use .filter() to keep only prices greater than 15, then use .reduce() to print their total.