I would like to extract a subtype from another type, but I don't know the most optimal/easiest way to do so.
I have many well-written (at least I think so) types in my project which could be generalized as:
interface Y {
readonly y: string
readonly type: 'y'
}
interface Z {
readonly z: number
readonly type: 'z'
}
interface X {
readonly prop: Y | Z
}
So in current shape it's simply not possible for me to extract only a subtype assignable to "Z", eg.
// the type evaluates to "never", I would like it to evaluate to "{ prop: Z }" instead
type ZfromX = Extract<X, {readonly prop: { readonly type: 'z' }}>
I know one of the approaches is to make the type to be a union instead of being a type consisting of nested unions, eg.
type X =
| {
readonly prop: Y
}
| {
readonly prop: Z
}
// now it works, the extracted type is "{ prop: Z }" as expected
type ZfromX = Extract<X, {readonly prop: { readonly type: 'z' }}>
But how to do so without rewriting every type which I have in my codebase into a union by hand? Maybe there is a way to transform each "branch" of my type into some kind of union of types made of cartesian product of branches (I could write that on my own, but maybe I'm not aware of an existing solution for that)?