我试图实例化一个类作为参数传递给另一个,我在一个文件ImportedClass.ts中有这个:

export default class ImportedClass {
  public constructor() {
  }
  public async exampleMethod() {
    return "hey";
  }
}


在另一个InstanceClass.ts中:

interface GenericInterface<T> {
  new(): T;
}

export default class InstanceClass <T extends { exampleMethod() }> {
  private c: GenericInterface<T>;
  public constructor(c: GenericInterface<T>) {
  }
  async work() {
    const instanceTry = new this.c();
    instanceTry.exampleMethod();
  }
}


这在另一个ClassCaller.ts中:

import ImportedClass from './ImportedClass';
import ImportedClass from './InstanceClass';

const simulator = new InstanceClass (ImportedClass);


然后当我这样称呼它时:

simulator.work();


它抛出此错误:

this.c is not a constructor

最佳答案

您忘了实际使用构造函数参数!

private c: GenericInterface<T>;
public constructor(c: GenericInterface<T>) {
}


您错过了:

private c: GenericInterface<T>;
public constructor(c: GenericInterface<T>) {
   this.c = c;
}


您可以改为执行此操作...自动映射!

public constructor(private c: GenericInterface<T>) {
}

09-17 09:07