TypeScript Generics Workshop (6 exercises)

Strongly Type a Reduce Function

Let's look at a practical example of passing type arguments.

Here we have an array.reduce which is being called on an array of objects with name keys.

This array is being changed into a new object where the keys are the names, then the item that's in the array is stuck onto that key.

Loading exercise


[0:00] [0: 00] Let's look at a practical example of passing type arguments now. Here we have array.reduce and array.reduce is basically calling this array and it's turning it into an object which looks like this where the keys are the names and it's grabbing the item that's in the array and sticking it on that key.
[0:19] [0: 20] What we're trying to achieve here is we're trying to achieve...Sure, we don't actually know the types or the names of the members up front. We're not expecting a really, really tight type here. We could do that and guess if we were using ask const, but for this exercise, we're not going to do that.

[0:34] [0: 34] Let's imagine this data is coming from an API or something and we don't know the members ahead of time at the type level.

[0:40] [0: 41] What we kind of want it to look like is a Record<string, { name.

: [0:44] [0: 44] string }>, but array.reduce currently what it's doing is this accumulator is just typed as an empty object. When we assign something to it, then it's saying, "No index signature with a parameter of type 'string' was found on type 'blah'."

[0:59] [1: 00] We somehow need to tell this reduce more information on the type level about the thing that we're trying to create in this accumulator.