[Typescript] 136. Medium - Object to Union

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

 

posted @ 2022-12-14 15:33  Zhentiw  阅读(21)  评论(0)    收藏  举报