External Libraries 9 exercises
Problem

Finding Proper Type Arguments and Generics with Lodash

Let's dive into this groupByAge function that uses groupBy from lodash.

The function takes in an array of objects, each with an age:


const groupByAge = (array: unknown[]) => {
const grouped = _.groupBy(array, "age");
return grouped;
};

Hovering over the example `resul

Loading exercise

Transcript

0:00 Knowing what we now know about exploring third-party libraries, let's dive into this groupBy age function, where we're importing something from Lodash, which is this groupBy. We're taking this array, which is currently typed as unknown array. We're grouping it by age.

0:16 This means that if we pass it in an array of objects, each with an age, then it's going to return a record where age is the index and with an array for the value. What this is going to do is it's going to mean that we can use this to categorize them into different spots and stuff.

0:32 It's an extremely useful function for all cases. This groupBy age function, currently the result is typed as _dictionary, unknown array. We're expecting it to be something like this, a dictionary with this instead.

0:52 Your job is to dive into the Lodash types, understand what dictionary means, understand what groupBy is supposed to accept, understand its generic signatures as well because we're going to need a generic here. If we have ID on this, for instance, ID 123, then that should be sent through to the result as well. This will need a generic function.

1:13 You'll need to understand a few things about Lodash's types that you'll need to investigate yourself. I'll come back with a solution. Good luck.