Mapped Types 9 exercises

Iteratively Map and Remap to Transform Types

Let's work through the solution step by step, following the outline from the problem.

First, we need to transform a discriminated union into a union of template literals.

We can do this by using a mapped type to get each member of the union:

type TransformedFruit = {
[F in Fruit as F["na

Loading solution


0:00 Let's live code this. What we want to do is first of all say, let's say F in Fruit and let's say we end up with fruit. Now this is tricky, because we've seen this before actually. We can't use Fruit here as an iterable. We can't use it as the key for this object.

0:21 What we can do is say Fruit as F name here. We end up with now apple Fruit, banana Fruit, orange Fruit. That's incorrect. This should be F instead, because that go back, this would be the entire fruit, the entire discriminated union we'd end up with. It's a little bit pointless.

0:41 We have access to F now, which is the individual fruit. We have apple name, apple color red, blah, blah, blah. What this means now is we can create. We have access to all of the pieces to create apple red, banana yellow, orange orange. Let's create that. We have F name and then F color.

1:03 Now we have apple red, banana yellow, orange orange. By creating that F, by doing this key remapping, we then understand that we have the member of the discriminated union there locked in the object that we can then manipulate.

1:21 The only thing left to us now is to basically take that discriminator, take the apple, banana, orange, and remap through this. We end up with F name here, sorry, or Fruit name, because fruits is the thing that we're doing. Fruit name, to reiterate, type FruitName = Fruit name.

1:44 What we have here then is apple or banana or orange. Because we've created this intermediary objects here, we use this to extract out the values and we're done. Let's take a look at the solution. Yes, it's exactly the same.

1:59 This pattern is so powerful as you can see. Thinking about it as an object that you're creating, then remapping to a different object and then iterating through the values of that object is a really useful way to think of iterators. Well done. Good work.