Unions and Indexing 10 exercises

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:

const fruits = ["apple", "banana", "orange"] as const

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

type Appl

Loading solution


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.