To sum it up, my goal is to develop a class that stores the type it will create (similar to a factory object). Here's an illustration of my issue using a selection of sample classes:
abstract class Shape {
size: number;
abstract getArea(): number;
}
class Square extends Shape {
getArea(): number { return this.size * this.size; }
}
class ShapeGenerator {
shapeType: typeof Shape;
createShape(): Shape { return new this.shapeType() } // This is where I encounter the challenge!
}
var squareGenerator = new ShapeGenerator();
squareGenerator.shapeType = Square;
var mySquare = squareGenerator.createShape();
mySquare.size = 5;
console.log(mySquare.getArea());
I want shapeType to indicate the class that will be created, but I aim to restrict it to something derived from Shape. Since I can't create an instance of Shape directly, I'm struggling to specify that shapeType will be derived from Shape, without being the abstract Shape class itself.
I'm uncertain if there is a way to use a type guard to clarify that this denotes a concrete class. Maybe there is an alternative approach I haven't yet considered. My current potential solutions include changing the return type of createShape to any or requiring a function as a constructor parameter to replace createShape entirely.