javascript - 实例泛型类抛出 "is not a constructor"

标签 javascript typescript generics typeerror

我试图实例化一个作为参数传递给另一个类的类,我将其放在一个文件中,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;
}

你可以这样做......自动 map !

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

关于javascript - 实例泛型类抛出 "is not a constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209910/

相关文章:

c# - 通用参数不可分配

python - 让 mypy 接受泛型类型的子类型作为方法参数

javascript - HTML 文件 API - 上传前图像/tiff 的宽度

javascript - 如果用户输入城市和州,则使用 zippopotam.us 自动填充邮政编码

javascript - onLoad 和 onunload 事件未触发

javascript - 存在多个查询参数时编写代码的更好方法

javascript - React 应用程序中除特定 DOM 节点之外的任何内容上的单击事件

angular - 我怎样才能 console.log 观察到的值?

reactjs - TypeScript 和 createContext - 类型上缺少属性

c# - 如何获取表单上的所有标签并将具有特定名称模式的标签的 Text 属性设置为 string.empty?