Overload of constructors in TypeScript

1

I am trying to make a class in TypeScript, in the following way:

You can receive a Array<Array<string>> only or you can receive several parameters ( ancho : number , blanco : string , trozo : string )

The implementation suggests me to use sobrecarga de constructores , but this is a problem since in TypeScript the created constructors must be compatible , so we must implement the constructors with all the class variables but not they are explicitly needed in that constructor, although they can be declared optional (In fact, a constructor is implemented that is compatible with all the others, the other constructors are simply declared):

PLUNK

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 any way to make this more understandable and readable?

    
asked by Jose Hermosilla Rodrigo 31.08.2016 в 19:35
source

2 answers

2

The following form is clean and simple:

class Piramide {

    constructor(
        public array?: string[][] | Array<any>,
        public ancho?: number,
        public blanco?: string,
        public trozo?: string
    ) {
        if(!array){
            this.ancho = ancho;
            this.blanco = blanco;
            this.trozo = trozo;
            this.array = [];
        }
        else
            this.ancho = array.length;
            ...
    }

    ...
}
    
answered by 13.09.2016 / 01:31
source
0

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

interface IPiramide {
    array? : Array<Array<string>>,
    ancho? : number,
    blanco? : string,
    trozo?  : string
}

class Piramide implements IPiramide {

    constructor(piramide : IPiramide){

        if(piramide.array){
            this.array = piramide.array;
            this.ancho = piramide.array.length;
        }
        else {
            this.array = [];
            this.ancho = piramide.ancho;
            this.blanco = piramide.blanco;
            this.trozo = piramide.trozo;
        }

    }
}
    
answered by 31.08.2016 в 19:36