Search code examples
typescriptunion-typeskeyof

Union type of keyof and Lookup Types pairs


From types like these:

type I1 = {
  a: number;
  b: boolean;
};

type I2 = {
  x: string;
  y: number;
};

I want to get types like these:

type O1 =
  | {
      name: "a";
      value: number;
    }
  | {
      name: "b";
      value: boolean;
    };

type O2 =
  | {
      name: "x";
      value: string;
    }
  | {
      name: "y";
      value: number;
    };

How can I define X so I can do:

type O1 = X<I1>;
type O2 = X<I2>;

Solution

  • Found this hack (improved with @Titian's comment):

    type X<I> ={ [k in keyof I]: { name: k; value: I[k]; } }[keyof I];