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

Typescript Using Class Types in Generics

I’m trying to make a factory method following the example in the docs on Using Class Types in Generics, however, I can’t get it to work.

Here is a minimal example of what I’m trying to do:

class Animal {
    legCount = 4;

    constructor(public name: string) { }
}

class Beetle extends Animal {
    legCount = 6;
}

const animalFactory = <T extends Animal>(animalClass: new () => T, name: string): T => {
    return new animalClass(name);
}

const myBug = animalFactory(Beetle, 'Fido');

However, I get the following errors:

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

error TS2554: Expected 0 arguments, but got 1.

return new animalClass(name);
                       ~~~~
---

error TS2345: Argument of type 'typeof Beetle' is not assignable to parameter of type 'new () => Beetle'.
  Types of construct signatures are incompatible.
    Type 'new (name: string) => Beetle' is not assignable to type 'new () => Beetle'.

const myBug = animalFactory(Beetle, 'Fido');
                            ~~~~~~

I also tried the alternative syntax for the class type mentioned in the docs;

animalClass: { new (): T } – but to no avail.

I don’t see where I’m going wrong with this…

>Solution :

It works when you add the constructor signature n: string.

const animalFactory = <T extends Animal>(animalClass: {new (n: string): T}, name: string): T => {
  return new animalClass(name);
}
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