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