I'm currently working on writing code that can handle generic discriminated unions with a type
property.
Imagine I have multiple discriminated unions defined as follows:
interface IFoo {
type: "foo";
foo: number;
}
interface IBar {
type: "bar";
bar: number;
}
interface IBaz {
type: "baz";
baz: number;
}
type IObject = IFoo | IBar | IBaz;
The first challenge I tackled was identifying the possible values of the type
property:
declare let _object: IObject;
type ObjectType = typeof _object.type;
(by the way, is there a way to do this without using an additional declare statement?)
Now, I need to define a generic type that can be used like so:
Case<IObject, "foo"> // = IFoo
Case<IObject, "bar"> // = IBar
This will allow me to create the following function:
function filter<Type extends ObjectType>(
objects: IObject[],
type: Type,
): Case<IObject, type>[] {
return objects.filter((o) => o.type == type);
}
Do you think this approach is feasible?