I am trying to make a class in TypeScript, like this:
It can receive Array<Array<string>>
only one or it can receive several parameters ( ancho : number
, blanco : string
, trozo : string
)
The implementation suggests me to use the sobrecarga de constructores
, but this is a problem since in TypeScript the constructors created must be compatible , so we must implement the constructors with all the class variables even if they are not explicitly needed in that constructor, although they can be declared optional ( In fact one constructor is implemented that is compatible with all the others, the other constructors are simply declared):
class Piramide {
public array : Array<Array<String>> | Array<any>;
public ancho : number;
public blanco : string;
public trozo : string;
constructor(array : Array<Array<String>> | Array<any>, ancho? : number, blanco? : string, trozo? : string);
constructor(array : Array<Array<String>> | Array<any>, ancho : number, blanco : string, trozo : string){
if(!array){
this.ancho = ancho;
this.blanco = blanco;
this.trozo = trozo;
this.array = [];
}
else
this.array = array;
this.ancho = array.length;
...
}
...
}
Is there a way to make this more understandable and readable?
The following form seems clean and simple to me:
You could simulate a "constructor overload" by checking the data type in the constructor.
You can use an interface, which is more flexible when declaring optional parameters. It can be used both as a parameter that the constructor receives, and as a prototype of the class that implements it:
PLUNK