Not a clue how to ask this well, so here is what I have and what I'm after:
Start:
type Initial = {
foo: string | number
}
End:
type Final = {
foo: string
} | {
foo: number
}
I need a type using generics that I can put Initial into that will output Final.
Edit: (Mapping through multiple union values) Playground Link
Edit 2 Thanks to the answer by Titian Cernicova-Dragomir I now have type that can distribute union values in an object into a union of objects, with no unions.
However:
The issue I'm now facing is, if I have multiple union values in an object:
type Initial = {
foo: string | number,
bar: "bar" | "anotherStr"
otherProp: string
}
type FinalNew = {
foo: string;
bar: "bar"
otherProp: string;
} | {
foo: number;
bar: "bar"
otherProp: string;
} | {
foo: string;
bar: "anotherStr"
otherProp: string;
} | {
foo: number;
bar: "anotherStr"
otherProp: string;
}
I can only change 1 union value in to a union of objects at a time:
type DistributedFoo = DistributeUnion<Initial, "foo">
type FinalNew = DistributeUnion<DistributedFoo, "bar">
I cannot do both in the same pass:
type FinalNew = DistributeUnion<Initial, "foo" | "bar">
The appended question then is:
- Is it possible to do this without having to assign the output type of
DistributeUnionto a newtypefor each key:value you need to distribute?
Initialhave other properties ? Or just the one ?