Feature Request - Overloaded & Default Constructors

Topics: General
Oct 18, 2013 at 10:34 PM
I was sad when I realized I couldn't use overloaded constructors and chaining them together. I was expecting to do something like:

// Properties
public SomeString: string;
public SomeString2: string;

// Default constructor
constructor() { }

// Pass to master
constructor(someString) :this(someString, null) { }

// Master constructor
constructor(someString: string, someString2: string)
{
 this.SomeString = someString;
 this.SomeString2 = someString2;
}
Developer
Oct 18, 2013 at 11:40 PM
This should do what you want:
class C {
     public SomeString: string;
     public SomeString2: string;

    constructor();
    constructor(someString: string);
    constructor(someString: string, someOtherString: string);
    constructor(anOptionalParam?: string, anOptionalParamWithDefaultValue = 'hello') {
        this.SomeString = anOptionalParam;
        this.SomeString2 = anOptionalParamWithDefaultValue;
    }
}

var c1 = new C();
console.log(c1.SomeString + ' ' + c1.SomeString2); // undefined Hello
//var c2 = new C(1); // error
var c3 = new C('a');
console.log(c3.SomeString + ' ' + c3.SomeString2); // a hello
var c4 = new C('a', 'b');
console.log(c4.SomeString + ' ' + c4.SomeString2); // a b
Oct 19, 2013 at 12:04 AM
Works like a charm. Thank you for your reply.