Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble with passing generic in Typescript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

VS Error

Many thank for any help.

>Solution :

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();
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading