Struggling to implement a factory method based on the example from the documentation on Using Class Types in Generics, but hitting roadblocks.
Here's a simplified version of what I'm attempting:
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');
Encountering 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');
~~~~~~
Even tried the alternative syntax for the class type as mentioned in the docs;
animalClass: { new (): T }
– but still facing issues.
Frustratingly, unable to pinpoint where the problem lies...