Map a Discriminated Union to an Object
We have a type Route
that is a discriminated union of the possible routes in the application. Each route has the properties search
and route
:
type Route = | { route: "/" search: { page: string perPage: string } } | { route: "/about"; search: {}
Transcript
0:00 We're now going to look at discriminated unions and turning them into objects. In a discriminated union, you always have essentially a key in the discriminated union. It's called the discriminator.
0:11 Here we have a bunch of routes with a bunch of searches in them. Each one has a route and a search. We want to turn it into an object where we have the route, which is the key, and then we have the search, which is going to be the value.
0:28 We know how to map over keys. We know how to extract values from discriminated unions as well. We know all of the pieces here, actually. It's just about putting them together and working out the correct way to do it.
0:42 There are two possible solutions. Both are fine. One is maybe more preferred than the other. Good luck.