Joseph Garrone
Joseph Garrone

Reputation: 1792

TypeScript: How to convert Record to union

Is it possible from this type:

type Input = {
    foo: "a" | "b";
    bar: "c" | "d";
};

to optain this type:

type Output = 
    { key: "foo"; value: "a" | "b"; } | 
    { key: "bar"; value: "c" | "d"; };

?
Thank you!

Upvotes: 1

Views: 919

Answers (1)

Federkun
Federkun

Reputation: 36989

Yeah, you can do that with mapped types.

type TransformInput<T> = {
  [P in keyof T]: { key: P; value: T[P] }; 
}[keyof T];

type Output = TransformInput<Input>

Output will evaluate to

type Output = {
    key: "foo";
    value: "a" | "b";
} | {
    key: "bar";
    value: "c" | "d";
}

Upvotes: 2

Related Questions