【发布时间】:2020-03-17 07:30:42
【问题描述】:
我正在动态创建子类,我希望工厂函数知道子类的返回类型。
我可以通过强制转换来做到这一点,但我想知道是否有一种方法可以在不需要强制转换的情况下推断它。
class Hello {
a = 1;
}
class Hello2 extends Hello{
b = 2;
}
class Hello3 extends Hello {
c = 3;
}
function create<T extends typeof Hello>(ctor: T): InstanceType<T> {
// If I don't cast this, it won't compile
return new ctor() as InstanceType<T>;
}
// Fails as it should because it's not a constructor of the right type
const h1 = create(Number);
const h2 = create(Hello2);
console.log(h2.b); // no error
const h3 = create(Hello3);
console.log(h3.c); // no error
【问题讨论】: