简体   繁体   English

传递类作为泛型参数打字稿

[英]Pass class as generic parameter Typescript

im trying to instance a class passed as parameter to another, I have this in one file, ImportedClass.ts:我试图实例化一个作为参数传递给另一个类的类,我在一个文件中拥有这个,ImportedClass.ts:

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

And this in another, InstanceClass.ts:这在另一个 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();
  }
}

And this in another, ClassCaller.ts: <--EDITED-->这在另一个 ClassCaller.ts 中:<--EDITED-->

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

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

Then when I call it like this:然后当我这样称呼它时:

simulator.work();

It throw this error:它抛出这个错误:

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

Any help is welcome, thanks.欢迎任何帮助,谢谢。

If T must have a method named exampleMethod you must include this in the constraint for T on Simulator to be able to use it inside Simulator :如果T必须有一个名为exampleMethod的方法,则必须将其包含在Simulator上的T的约束中,以便能够在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 游乐场链接

There were other small issues that needed to be fixed to make the snippet above work, but that is the mai issue.还有其他一些小问题需要修复才能使上述代码段正常工作,但这是主要问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM