Constructor overload in TypeScript

前端 未结 16 2089
滥情空心
滥情空心 2020-11-28 00:42

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 wa

16条回答
  •  被撕碎了的回忆
    2020-11-28 01:22

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

提交回复
热议问题