Home > Mobile >  Typescript Using Class Types in Generics
Typescript Using Class Types in Generics

Time:04-08

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:

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...

CodePudding user response:

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);
}
  • Related