Type Transformations Workshop 0 exercises
solution

Map an Object to a Union of Template Literals

Let's build the solution step by step.

We know that we need to start by using a mapped type to transform the object.

Since we are working with an object, we can use the keyof operator to get the keys and use them in the value:


type TransformedFruit = {
[K in keyof FruitMap]: K
}

H

Loading solution

Transcript

0:00 I'm going to live-code this one just to show you my exact thought process as I'm going through each section. We know, or at least I feel here when I see this, I want to use a mapped type of some sort. That's where I go whenever I need to transform an object to a union type.

0:17 I can see that we have an object here. That makes me think of K in keyof FruitMap. I now have access to this K in keyof here. I have access to each K, which is super-useful. I like creating these intermediary representations so I can constantly go back and forth and hover over them and see what I've got.

0:39 I've got apple apple, banana banana, orange orange. That means then that if I end up with going keyof FruitMap here, then I'm going to end up with orange or apple or banana. That's a pretty good start.

0:51 Let me remove that. That means now that I've got the first part of this little template literal I need to create. I'm going to wrap this in a template literal and give it this. Now we've got apple apple, banana banana, orange orange. That's good. That means I can then say FruitMap and and access it using an indexed access type.

1:14 Now, I've actually got all of the pieces I need apple red, banana yellow, orange orange. That means I know that when I've reached this intermediary representation, which is the keys are all I need, then all I need to do is access them using keyof FruitMap. I end up with orange orange, apple red, banana yellow.

1:34 Let's see how I compare to my own solution. Nice. I called it F, but it's exactly the same solution here. You can start to see how powerful this is. We really can do any type of transformation here because we're iterating over each member of the object. The only really unintuitive bit is this section here, where we then extract out the values from this keyed object that we've got there.