Type Transformations Workshop (9 exercises)
solution

Use Mapped Types to Create an Object from a Union

The Mapped Type solution includes some new syntax:

The [R in Route] part looks similar to an index, but it isn't.

Loading solution

Transcript

0:00 The solution introduces a few new bits of syntax here. This setup where we have basically an object type here, and inside here we create like an index in here. Except it's not really an index. You can do like index, string is string or something like that. You end up with basically something that's equivalent to Record, string, string, which is where you can add any elements to it and they all have to be strings.

0:29 Here what we're doing is we're kind of mapping over something. We're saying R in Route is R. What we end up with there is if we hover over it, we can see each of the members. This R in Route, what we're saying basically is for each member of the Route union, extract our R into a private variable, into something that we can access here, and add it as the value.

0:57 In here, we could have string instead. Now we get the string, about, string, admin, string. Whereas here, what we're doing is we've now got direct access to that R. I can even change this if I want to. I can add something manual in here and say "wow," for instance. Here, what we have then is we're...You see what I mean? We can just map over pretty much any union in here and create an object out of it.

1:22 This is super fascinating. This map type gives you an enormous amount of power in TypeScript due to some patterns that we can use this for later on. For now, what I want you to think about is how would you use this in your day-to-day practice? What can you create out of this? You notice here, we don't have to pass R. We can pass R or undefined. We can do any sort of manipulation we want to.

1:50 Let's say we want to make this into this or undefined. You don't have to pass each of these. Then we can do that too. This is an extremely powerful construct, and this is only the beginning.