zl程序教程

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

当前栏目

[Typescript] 136. Medium - Object to Union

typescript to object union Medium 136
2023-09-14 08:59:11 时间
import { Equal, Expect } from "../helpers/type-utils";

interface Attributes {
  id: string;
  email: string;
  username: string;
}

/**
 * How do we create a type helper that represents a union
 * of all possible combinations of Attributes?
 */
type ObjectToUnion<T> = {
  [Key in keyof T]: Record<Key, T[Key]>;
}[keyof T];

type ExclusiveAttributes = ObjectToUnion<Attributes>;

type tests = [
  Expect<
    Equal<
      ExclusiveAttributes,
      | {
          id: string;
        }
      | {
          email: string;
        }
      | {
          username: string;
        }
    >
  >
];