TypeScript allows you to declare overloads but you can only have one implementation and that implementation must have a signature that is compatible with all overloads. Some techniques for constructor overloading are:
- with an optional parameter as in
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
constructor();
constructor(obj: IBox);
constructor(obj?: any) {
this.x = obj && obj.x || 0
this.y = obj && obj.y || 0
this.height = obj && obj.height || 0
this.width = obj && obj.width || 0;
}
}
- default parameters
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {
this.x = obj.x;
this.y = obj.y;
this.height = obj.height;
this.width = obj.width;
}
}
- additional overloads as static factory methods
class Person {
static fromData(data: PersonData) {
let { first, last, birthday, gender = 'M' } = data
return new this(
`${last}, ${first}`,
calculateAge(birthday),
gender
)
}
constructor(
public fullName: string,
public age: number,
public gender: 'M' | 'F'
) {}
}
interface PersonData {
first: string
last: string
birthday: string
gender?: 'M' | 'F'
}
let personA = new Person('Doe, John', 31, 'M')
let personB = Person.fromData({
first: 'John',
last: 'Doe',
birthday: '10-09-1986'
})
- using union types
class foo {
private _name: any;
constructor(name: string | number) {
this._name = name;
}
}
var f1 = new foo("bar");
var f2 = new foo(1);