Utility type to "undiscriminate" a discriminated union

So this might be kind of a hacky thing, but I've got a use case that could greatly benefit from it. Basically, imagine I have the following type:
type DiscriminatedUnion = {
type: "image"
imageUrl: string
} | {
type: "text"
body: string
}
type DiscriminatedUnion = {
type: "image"
imageUrl: string
} | {
type: "text"
body: string
}
I've been trying to make a utility type essentially flatten this type into something like this:
type FlattenDiscriminatedUnion<Union, Field extends string> = {
// ?????
}

// FlattenDiscriminatedUnion<DiscriminatedUnion, "type"> === {
// type: "image" | "text"
// imageUrl?: string
// body?: string
//}
type FlattenDiscriminatedUnion<Union, Field extends string> = {
// ?????
}

// FlattenDiscriminatedUnion<DiscriminatedUnion, "type"> === {
// type: "image" | "text"
// imageUrl?: string
// body?: string
//}
This may be pushing the limits of TS, but was hoping some wizardry could be done to solve this. Does this sound like something that's even possible? I've been trying to make it happen for a while but can't seem to get it to work.
1 Reply
Matvey
Matvey16mo ago
DEV Community
Union Type Merging in Typescript
Typescript unions can be very useful in a lot of cases. They can be used to implement algebraic data...
Want results from more Discord servers?
Add your server