How to implement constructor overloading in TypeScript properly?

Has anyone implemented constructor overloading in TypeScript? I read about constructor overloads in the TypeScript language specification (v0.8) on page 64, but there were no sample codes provided. Here’s a basic class declaration I’m trying:

interface IBox {
x: number; y: number; height: number; width: number; }

class Box { public x: number; public y: number; public height: number; public width: number;

constructor(obj: IBox); // Constructor overload
constructor(); // Constructor overload
constructor(obj?: IBox) { // Implementation of the constructor
    if (obj) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    } else {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

}

When I run tsc BoxSample.ts, it throws an error about duplicate constructor definitions. How can I properly implement constructor overloading in TypeScript?

Hey MattD,

Define Constructor Overloads with Method Signatures : Define the overloads as method signatures and then implement a single constructor that handles the logic based on the provided arguments.

interface IBox {
x: number; y: number; height: number; width: number; }

class Box { public x: number; public y: number; public height: number; public width: number;

constructor(obj: IBox);
constructor();
constructor(obj?: IBox) {
    if (obj) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    } else {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

}

Hello MattD,

Define Constructor Overloads with Method Signatures : Define the overloads as method signatures and then implement a single constructor that handles the logic based on the provided arguments.

interface IBox {
x: number; y: number; height: number; width: number; }

class Box { public x: number; public y: number; public height: number; public width: number;

constructor(obj: IBox);
constructor();
constructor(obj?: IBox) {
    if (obj) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    } else {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

}