zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Typescript] Map a Discriminated Union to an Object

Maptypescript to object an union
2023-09-14 08:59:11 时间

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"];
};