Unions and Indexing 10 exercises
solution

Simple Syntax Used to Access Parts of a Discriminated Union

As simple as it may seem, here’s the solution:


type EventType = Event["type"];

This works because when you access a key in a union type, you are actually accessing every possible permutation of the union.

Experimenting with the Event Type

For example, let’s remove the type disc

Loading solution

Transcript

0:00 Here you go. This is the solution. As simple as it may seem, when you access a key on a union, you're actually accessing all of the possible permutations of that key. It means that EventType ends up being click or focus or keydown.

0:17 If I were to remove the discriminator here, this would actually not work because it doesn't exist on all of the different branches of the union. It works especially well with discriminated unions because you know in a discriminated union, like type, is always going to be there.

0:32 Whereas we could do this with the Event, for instance, so Event "event," and we'd end up with MouseEvent or FocusEvent or KeyboardEvent. If one of these was actually mislabeled as mouseEvent, like this for instance, then this wouldn't work.

0:46 That's a really important thing to understand about these types is that you can actually access pieces of them as long as they belong on each member of the union.