通过类作为通用参数Typescript

时间:2018-11-07 14:17:54

标签: javascript typescript class generics

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

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

这是另一个InstanceClass.ts:

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

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

然后在另一个ClassCaller.ts中:<-编辑->

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

const simulator = new InstanceClass <ImportedClass>(ImportedClass);

然后当我这样称呼它时:

simulator.work();

它抛出此错误:

error TS2339: Property 'exampleMethod' does not exist on type 'T'.

欢迎您的帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

如果T必须具有名为exampleMethod的方法,则必须将此方法包含在T上的Simulator的约束中,以便能够在Simulator中使用它:

export class ImportedClass {
    public constructor(something: any) {
    }
    public async exampleMethod() {
        return "hey";
    }
}

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

export class Simulator<T extends { exampleMethod(): Promise<string> }> {
    public constructor(private c: GenericInterface<T>) {
    }
    async work() {
        const instanceTry = new this.c("hello");
        await instanceTry.exampleMethod();
    }
}
const simulator = new Simulator(ImportedClass);
simulator.work()

Playground link

还有其他一些小问题需要修复,以使摘要片段正常工作,但这就是mai问题。