我想建立一个结构,我可以在下面的代码中创建从ClassReturner和TheClass扩展的新类,但是我收到了错误。
abstract class ClassReturner <TClass extends TheClass> {
private returningClass : TClass;
constructor ( r : TClass ){
this.returningClass = r;
}
public getAnotherClass (){
//ERROR BELOW: Cannot use 'new' with an expression whose type lacks a call or construct signature.
return new this.returningClass("John Doe");
}
}
abstract class TheClass {
private whoiam: string;
constructor ( w : string ){
this.whoiam = w;
}
}
为什么不允许这样做? TClass
扩展TheClass
的事实不应该确认它有构造函数吗?
答案 0 :(得分:2)
不,returningClass: TClass
是扩展TheClass
的类的实例
要拥有你需要的人:{ new (name: string): TheClass }
。
所以这对你有用:
abstract class TheClass {
private whoiam: string;
constructor(w: string) {
this.whoiam = w;
}
}
interface TheClassConstructor<T extends TheClass> {
new(name: string): T;
}
abstract class ClassReturner<TClass extends TheClass> {
private returningClass: TheClassConstructor<TClass>;
constructor(r: TheClassConstructor<TClass>) {
this.returningClass = r;
}
public getAnotherClass() {
return new this.returningClass("John Doe");
}
}