首页 > 其他分享 >[Typescript] 137. Hard - Discriminated union to Object

[Typescript] 137. Hard - Discriminated union to Object

时间:2022-12-14 16:25:39浏览次数:55  
标签:Typescript string union unknown route Object admin 137 type

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

 

标签:Typescript,string,union,unknown,route,Object,admin,137,type
From: https://www.cnblogs.com/Answer1215/p/16982451.html

相关文章