Unions and Indexing 10 exercises

Extracting Members of a Discriminated Union

Here we have a discriminated union called Event which has a discriminator called type on it:

export type Event =
| {
type: "click"
event: MouseEvent
| {
type: "focus"
event: FocusEvent
| {
type: "keydown"
event: KeyboardEvent

Loading exercise


0:00 We've got a discriminated union here, which is like an event, which has this type discriminator on it. What we want to do is to extract a type from this discriminated union.

0:12 We want to extract this little click type here. We want to put it inside ClickEvent and say that the type is click and the event is MouseEvent.

0:22 Again, we could just say, type: "click" and then event: MouseEvent in here. Ideally, we want to be able to save lines of code and extract from one to the other. We don't need to double declare this.

0:37 Your job is to use a utility type here, to help you out, and you're probably going to need...No, that's all the clue I'm going to give you. Good luck.