Home > Software design >  Trouble with passing generic in Typescript
Trouble with passing generic in Typescript

Time:02-19

I'm new to typescript, trying to achieve writing method with an generic type argument like in .Net.

Following the sample code :

class TestObject {
  Id: number;
  Truc: string;
  Machin: string;
}

export default
  {

    async FirstMethod(): Promise<TestObject> {
      return await this.TestMethodGen<TestObject>();
    },

    async TestMethodGen<T>(): Promise<T>  {
      // Json Deserialization other etc ...
      return <T>new Object();
    }
  }

How over type script error TS2347 occurs and i can't figure out why.

TS2347 (TS) Untyped function calls may not accept type arguments.

VS Error

Many thank for any help.

CodePudding user response:

According to the TypeScript documentation.

When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions.

The following works fine on my setup.

class TestObject {
    Id: number;
    Truc: string;
    Machin: string;
}

export default {
    async FirstMethod(): Promise<TestObject> {
        return await this.TestMethodGen(TestObject);
    },

    async TestMethodGen<T>(c: { new (): T }): Promise<T> {
        // Json Deserialization other etc ...
        return new c();
    }
};
  • Related