I am currently developing a class system using Typescript. The main structure consists of an abstract class called Component
, which includes a static method called create()
. This method is utilized on child classes to generate specific instances.
abstract class Component {
static build() {
// additional logic can be added here, like caching to reuse instances
return new this();
}
}
class Button extends Component { }
class Input extends Component {}
Button.build(); // generates a Button instance
Input.build(); // generates an Input instance
Code available in TS Playground
Although this approach functions effectively in Javascript, it causes an error in Typescript at the line where new this()
is triggered, with a message saying "Cannot create an instance of an abstract class."
Is there a way to inform Typescript that the method should only be invoked on derived instances and not directly on the main abstract class? Are there alternative methods to implement the required API?