Challenges 5 exercises
Problem

Narrowing with an Array

In this exercise, we will review a couple things we learned about identity functions.

Here we have a wrapFruit function that takes an array of fruits, each with a name and a price, and returns an object with a getFruit function. The getFruit function takes in the fruit name and returns the fr

Loading exercise

Transcript

0:00 In this exercise, we're going to review some of the stuff we did in the identity functions section. We have a wrapFruit function here. What it does is it takes in some fruit, and these fruits have to be constrained to a certain type, so name and price.

0:15 We want these to be inferred to their literals so that we can then...Fruits doesn't actually return an array here. It actually returns an object of getFruit. GetFruit, what it does, it takes in the name, so the name of a fruit, so this will be apple or banana. What it does is it finds that fruit and returns that specific fruit.

0:37 We need to make this work on the type level as well. When we get back banana, we're expecting banana to be a readonly name, "banana"; readonly price, 2, and we're expecting apple to be readonly name, "apple"; readonly price, 1.

0:52 That's your challenge. You're going to probably need some const generics. You'll need some constraints. You're going to need to do a little bit of type transformation here as well in order to extract out the correct fruit.

1:03 You're probably going to need to patch over some of JavaScript here because, for instance, find always returns unknown or the thing that you're finding.

1:13 You're probably going to need to assert that the thing that you're returning is the thing because we know on the type level that getFruit is always going to return the thing. It's not going to return the thing or undefined. It's always going to have a member to find there, basically.

1:30 Good luck, and I'll see you on the other side.