【发布时间】:2021-02-07 03:19:38
【问题描述】:
我的类的构造函数需要形成标记联合的对象:
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;
我省略了类内部和构造函数初始化。如何键入此工厂函数以关联根据传入的信息创建的对象类型?
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
【问题讨论】:
标签: typescript generics typescript-typings