首页 > 其他分享 >[Typescript] Transform a Discriminated Union into a Union

[Typescript] Transform a Discriminated Union into a Union

时间:2022-12-13 15:58:30浏览次数:57  
标签:name Union into Discriminated Fruit orange type color apple

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

 

标签:name,Union,into,Discriminated,Fruit,orange,type,color,apple
From: https://www.cnblogs.com/Answer1215/p/16979008.html

相关文章