Constructor overload in TypeScript

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

    You can handle this by :

    class Box {
      x: number;
      y: number;
      height: number;
      width: number;
      constructor(obj?: Partial) {    
         assign(this, obj);
      }
    }
    

    Partial will make your fields (x,y, height, width) optionals, allowing multiple constructors

    eg: you can do new Box({x,y}) without height, and width.

提交回复
热议问题