As a Java developer who is grappling with Typescript, I am faced with a challenge in implementing an abstract class called Shape and two concrete classes (Square and Circle) that inherit from it. My goal is to hide the constructor for these classes and instead create a factory method named getNewShape. This method will determine which concrete constructor to use based on an argument provided. In Java, achieving this would be straightforward by writing the following code snippet inside the Shape class:
public static <T extends Shape> T getNewShape(T reference){
// my logic
reference = T.class.getInstance();
return reference;
}
In Typescript, I would like to implement it as follows:
let myShape = Square.getNewShape(myShape);
I have come across suggestions to handle this issue using the following approach:
For the consumer:
let myShape = Square.getNewShape(myShape, Square);
Inside the Shape class:
public static <T extends Shape>(ref: T, type): T{
//my logic
reference = new type();
return reference;
}
However, I would prefer if TypeScript could infer the Type parameter automatically when calling getNewShape from the concrete classes, without needing to explicitly specify it in the parameters.
Update: Including the complete code sample below:
class Shape {
constructor(){
}
public static getNewShape<T extends Shape>(ref: T, type: new() => T): T{
if(ref) {
ref.clear();
}
ref = new type();
return ref;
}
protected clear(){
console.log('clearing');
}
}
class Circle extends Shape{
protected constructor(){
super();
}
}
class Square extends Shape{
protected constructor(){
super();
}
}
class App {
private _circle: Circle = null;
constructor(){
}
public setup(){
this._circle = Circle.getNewShape(this._circle, Circle);
}
}