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;
}
}
}
Hey MattD,
Here is the answer to the Question:-
Use a Factory Method for Different Constructors : You can use static factory methods to handle different initialization scenarios. This approach avoids constructor overloading and provides a clear API for different ways of creating instances.
interface IBox {
x: number;
y: number;
height: number;
width: number;
}
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
private constructor(x: number, y: number, height: number, width: number) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
public static fromObject(obj: IBox): Box {
return new Box(obj.x, obj.y, obj.height, obj.width);
}
public static default(): Box {
return new Box(0, 0, 0, 0);
}
}
// Usage
const box1 = Box.fromObject({ x: 10, y: 20, height: 30, width: 40 });
const box2 = Box.default();