[Typescript] Transform a Discriminated Union into a Union

Consider this discriminated union called Fruit:

type Fruit =
  | {
      name: "apple";
      color: "red";
    }
  | {
      name: "banana";
      color: "yellow";
    }
  | {
      name: "orange";
      color: "orange";
    };

 

We want transform it to:

type tests = [
  Expect<
    Equal<TransformedFruit, "apple:red" | "banana:yellow" | "orange:orange">
  >
];

 

Solution:

type TransformedFruit = {
  [F in Fruit as F["name"]]: `${F["name"]}:${F["color"]}`;
}[Fruit["name"]];

 

so for discriminated union, if we do: Fruit["name"], what we got is:

Fruit["name"] // "apple" | "banana" | "orange"

Which means, as long as we can construct such type:

{
    apple: "apple:red";
    banana: "banana:yellow";
    orange: "orange:orange";
}

problem will be resolved:

type TransformedFruit = {
  [F in Fruit as F["name"]]: `${F["name"]}:${F["color"]}`;
};

Now, we just need to map over it:

type TransformedFruit = {
  [F in Fruit as F["name"]]: `${F["name"]}:${F["color"]}`;
}[Fruit["name"]];

 

posted @ 2022-12-13 15:42  Zhentiw  阅读(36)  评论(0)    收藏  举报