I have classes whose constructors require objects which form a tagged union:
interface Info {
x: string;
}
interface AInfo extends Info {
x: 'a';
}
class A {
constructor(info: AInfo) {}
}
interface BInfo extends Info {
x: 'b';
}
class B {
constructor(info: BInfo) {}
}
type AllInfos = AInfo|BInfo;
I've omitted class internals and constructor initialization. How can I type this factory function to correlate the type of object created based on the info passed in?
const factory = (info: AllInfos) => {
switch (info.x) {
case 'a': return new A(info);
case 'b': return new B(info);
// ...
}
};
const obj = factory(myInfo); // type of obj is A|B, I'd like it to vary by myInfo