Challenges 5 exercises

Narrowing with an Array

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

This wrapFruit function 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 fruit object that matches the name:

Loading exercise


0:00 In this exercise, we're going to review a couple of things we learned in the identity functions module. We have this wrapFruit function. It takes in an array of fruits here, which each have a name and a price.

0:14 What we're going to do is we're going to say when we call this function, we're going to get back an object which has getFruit on it. This is going to be a method that takes in name unknown and returns unknown, currently, but it finds the fruit which has the same name as the one that you passed in.

0:33 What we're doing here is we're saying, "fruits.getFruit." We're expecting autocomplete here. When we say like...It should say banana or apple because we've got apple or banana being mixed in here. We shouldn't be able to pass in something that isn't allowed here, so something that's not been specified there.

0:51 In these tests, the thing that's returned here should be the exact type that we passed in here, so literals and all, so like name apple, price 1, instead of it being name string, price number, let's say.

1:05 That's your challenge, is to work out how you can figure out the types for this and how you can type this getFruit function. You're definitely going to need some generics here. You might need something from the ts-toolbelt library. Good luck.