Mapped Types 9 exercises

Create a Union of Tuples by Reindexing a Mapped Type

In order to create a union of tuples, we need to extract the values of the object that is currently being created:

email: ["email", string]
firstName: ["firstName", string]
lastName: ["lastName", string]

The solution is to re-index the type we started with by appending `[keyof

Loading solution


0:00 We're going to start with the problem here. Inside ValuesAsUnionOfTuples, we now have an object where we have email is email string, firstName is firstName string, lastName is lastName is string.

0:13 All we need to do here is extract out the values from this object. If we can do that, we'll end up with a union of email string, firstName string, and lastName string, which is where we want to be. The way you do that normally is let's say you have a type Obj equals...Let's say ValuesObjectValues -- lovely name -- equals values key of values.

0:42 If we change one of these, let's say we have age number here, for instance, then we're going to end up with string or number. What's going on here is we're just extracting out the values from this interface. If we remove that, we just end up with string, of course.

0:57 The solution here is to use the keys that we're getting here to re-index these values as a union of tuples, meaning the solution is keyof Values. How mad does that look? That looks just insane. This is the solution here.

1:16 What we end up with then is we basically create an intermediary representation where we have this keyed object with the values we want to turn into a union, and then we remap over that using the same key, and we end up with exactly what we need.

1:33 It's hard to overstate how useful this pattern is. It looks completely mad when you first see it, but my God, you can actually use this in lots of different ways to map over unions, transform them into different unions, transform them into objects.

1:49 It's extremely versatile. It was one of the first patterns I learned when I entered Wizards Hogwarts or whatever, Typescript Hogwarts. I used everywhere. This is extremely powerful stuff and we're going to continue using it in this section.