[Typescript] 137. Hard - Discriminated union to Object

import { Equal, Expect } from "../helpers/type-utils";

type Route =
  | {
      route: "/";
      search: {
        page: string;
        perPage: string;
      };
    }
  | { route: "/about" }
  | { route: "/admin" }
  | { route: "/admin/users" };

type DiscrimatedUnionToObject<
  T extends Record<PropertyKey, any>,
  U extends keyof T
> = {
  [P in T as P[U]]: [Exclude<keyof P, U>] extends [never]
    ? unknown
    : {
        [Key in Exclude<keyof P, U>]: P[Key];
      };
};

type tests = [
  Expect<
    Equal<
      DiscrimatedUnionToObject<Route, "route">,
      {
        "/": {
          search: {
            page: string;
            perPage: string;
          };
        };
        "/about": unknown;
        "/admin": unknown;
        "/admin/users": unknown;
      }
    >
  >
];

 

posted @ 2022-12-14 16:07  Zhentiw  阅读(27)  评论(0)    收藏  举报