Constructor overload in TypeScript

前端 未结 16 2052
滥情空心
滥情空心 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:38

    Note that you can also work around the lack of overloading at the implementation level through default parameters in TypeScript, e.g.:

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

    Edit: As of Dec 5 '16, see Benson's answer for a more elaborate solution that allows more flexibility.

提交回复
热议问题