Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor overload in TypeScript

Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given.

I'm trying out a really basic class declaration right now; it looks like this,

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) {             this.x = obj.x;         this.y = obj.y;         this.height = obj.height;         this.width = obj.width;     }         constructor() {         this.x = 0;         this.y = 0;         this.width = 0;         this.height = 0;     } } 

When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious. Any help is appreciated.

like image 309
Ted Avatar asked Oct 03 '12 05:10

Ted


People also ask

Is there constructor overloading in TypeScript?

TypeScript also supports constructor overloading; however, it is different from the conventional constructor overloading found in languages like C++ or Java.

How many constructors can a class have in TypeScript?

But in TypeScript, unlike any other object-oriented language, only one constructor is allowed.

Can we have 2 constructors in angular?

error TS2392: Multiple constructor implementations are not allowed.

Can a class overload properties in TypeScript?

Method overloading in Typescript differs from traditional programming languages like Java or C#. To overload methods, you can either choose optional parameters or function declarations.


1 Answers

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. In your example, this can easily be done with an optional parameter as in,

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) {             this.x = obj?.x ?? 0         this.y = obj?.y ?? 0         this.height = obj?.height ?? 0         this.width = obj?.width ?? 0;     }    } 

or two overloads with a more general constructor as in,

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();     constructor(obj: IBox);      constructor(obj?: IBox) {             this.x = obj?.x ?? 0         this.y = obj?.y ?? 0         this.height = obj?.height ?? 0         this.width = obj?.width ?? 0;     }    } 

See in Playground

like image 133
chuckj Avatar answered Sep 21 '22 13:09

chuckj