1

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

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.