Type Transformations Workshop (8 exercises)
solution

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:

The solution is to re-index the type we started with by appending [keyof Values] to the end of it.

Before:

After:

With [keyof Values] appended, we are creating an intermediary object that contains the values we want, but then remapping over it using the same key.

This results in the union of tuples we wanted:

While this syntax looks odd at first, this pattern can be used in many different ways. It's hard to overstate how useful it is!

Transcript

[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.