...

/

Generic Functions Example - Typing `reduce`

Generic Functions Example - Typing `reduce`

This lesson walks through the implementation of an example generic function. Typing array utility functions is a great exercise that helps you fully understand the complexities of generics.

What is reduce?

Array.reduce is an extremely versatile function that lets you calculate results from all elements of an array. When calling reduce you specify a function that describes how to calculate the result for the next array element, given you already know the result for the previous array elements. It’s like a functional version of a foreach loop with an additional variable that you change in the loop and return at the end.

Press + to interact
const sum = [1, 2, 3, 4, 5].reduce((sum, el) => sum + el, 0);
console.log(sum);
interface Person {
name: string;
age: number;
}
const persons: Person[] = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 45 },
];
const ageByPerson = persons.reduce((result, person) => ({
...result,
[person.name]: person.age
}), {});
console.log(ageByPerson);

Our reduce ...