Attempting to segregate a discriminated union array into separate arrays of its union types has presented some challenges. I came across this particular question that provides generic discriminators.
Unfortunately, the dataset I am working with doesn't have the discriminator key at the topmost level.
type Foo = { meta: {type: "Foo"} };
type Goo = { meta: {type: "Goo"} };
type Union = Foo | Goo;
To address this issue, I made modifications by adjusting the discriminator function mentioned in the aforementioned post to anticipate the inclusion of the "meta" object one level beneath.
function discriminateNested<K extends PropertyKey, V extends string | number | boolean>(
discriminantKey: K, discriminantValue: V
) {
return <T extends Record<PropertyKey, any>>(
obj: T & Record<"meta", Record<K, V extends T["meta"][K] ? T["meta"][K] : V>>
): obj is Extract<T, Record<"meta", Record<K, V>>> =>
obj["meta"][discriminantKey] === discriminantValue;
}
Is there a more general approach to handle this? Perhaps by defining a nested key as a string like
discriminateNested("meta.type", "Foo")
?