2

im trying to instance a class passed as parameter to another, I have this in one file, ImportedClass.ts:

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

And this in another, 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-->

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.

1 Answer 1

1

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:

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.

2
  • Thanks for the answer, <T extends { exampleMethod() }> i extended it but still get this error: TS2345: Argument of type 'typeof ImportedClass' is not assignable to parameter of type '{ exampleMethod(): any; }'. Property 'exampleMethod' is missing in type 'typeof ImportedClass'. Again thanks. Commented Nov 7, 2018 at 15:32
  • @user3314345 Your parameter to the constructor of Simulator was T you want it to be the constructor (GenericInterface<T>), check my sample code and the playground link. Commented Nov 7, 2018 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.