Type Transformations Workshop (9 exercises)
solution

Methods Used to Create Unions out of Array Values

Apple or Banana

The first thing to do is use as const on the fruits array so that each element is a literal type:

Then use typeof fruits to access into the array using an indexed access type with 0 | 1:

Remember the numbers correspond to the fruits array.

Changing 1 to 2 will get orange instead of apple. However, changing 1 to 3 results in an error since we don't have an element at index 3.

All of the Fruits

We can follow the same pattern as above to get all of the fruits, but this breaks down when we add more elements to the array.

First we need to pass number to the indexed access type:

Here number acts as any possible number, so we get the union of all of the elements in the array.

This is a new syntax that's super neat, and very useful for creating a union out of every element of an array.

Transcript

[0:00] The solution here is in three parts. First of all, we want to use as const to make sure that all of the fruits here are typed as their literal values. Without this, we can't do any of the other pieces. That's pretty important first.
[0:14] The second one is that we want to use typeof fruits and then access into the array using an indexed access type using a union that we've seen before.

[0:24] Now, this AppleOrBanana results in apple or banana. If I change this to two for instance, then we get apple or orange instead. If I change this to three, then three is not assignable. It doesn't have an element at index three, which is interesting.

[0:39] Now, if I want to get all of the fruits here, I can either say, zero or one or two in here, and that will get me all the fruits. That's fine. If I had third one or a fourth one, rather, then that's not going to work.

[0:53] What I want to do is get all of the elements of this tuple now, like two end a time. Get all of them possible. You can pass in number here and number will work as zero or one or two or however long the array is, it will go in and get all of the elements.

[1:14] This syntax is like the new one here that we've not seen before and it's pretty neat, like this. This lets you access any member of the array and it turns it into a union.