[Typescript] 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: {} }
| { route: "/admin"; search: {} }
| { route: "/admin/users"; search: {} };
Expected:
type tests = [
Expect<
Equal<
RoutesObject,
{
"/": {
page: string;
perPage: string;
};
"/about": {};
"/admin": {};
"/admin/users": {};
}
>
>
];
Way to solve the problem is by Extract the actual route type based on discriminated type:
type RoutesObject = {
[Key in Route["route"]]: Extract<Route, { route: Key }>["search"];
};
A second apparoach:
type RoutesObject = {
[R in Route as R["route"]]: R["search"];
};