Unions and Indexing 10 exercises
solution

Use a Utility Type to Remove a Single Member of a Union

The solution here is to use the Exclude utility type.


type NonKeyDownEvents = Exclude<Event, { type: "keydown" }>

The Exclude utility type operates similarly to Extract, but this time we are excluding the keydown type from the union.

If you've got several members of a u

Loading solution

Transcript

0:00 The solution here is to use Exclude, which operates just like Extract, but in reverse. Instead of extracting out the type of key down, we're now just excluding it from the union. It's as though it never even existed. This is really, really useful when you have a union, and you just want to extract a small part of it.

0:19 You can see here that we actually just end up with a different union just with that little bit removed. Exclude is the right word. It's like you've got this group of things and you just want to remove one of them. Then Exclude is great for that.