Constructor overload in TypeScript

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

    Update 2 (28 September 2020): This language is constantly evolving, and so if you can use Partial (introduced in v2.1) then this is now my preferred way to achieve this.

    class Box {
       x: number;
       y: number;
       height: number;
       width: number;
    
       public constructor(b: Partial = {}) {
          Object.assign(this, b);
       }
    }
    
    // Example use
    const a = new Box();
    const b = new Box({x: 10, height: 99});
    const c = new Box({foo: 10});          // Will fail to compile
    

    Update (8 June 2017): guyarad and snolflake make valid points in their comments below to my answer. I would recommend readers look at the answers by Benson, Joe and snolflake who have better answers than mine.*

    Original Answer (27 January 2014)

    Another example of how to achieve constructor overloading:

    class DateHour {
    
      private date: Date;
      private relativeHour: number;
    
      constructor(year: number, month: number, day: number, relativeHour: number);
      constructor(date: Date, relativeHour: number);
      constructor(dateOrYear: any, monthOrRelativeHour: number, day?: number, relativeHour?: number) {
        if (typeof dateOrYear === "number") {
          this.date = new Date(dateOrYear, monthOrRelativeHour, day);
          this.relativeHour = relativeHour;
        } else {
          var date =  dateOrYear;
          this.date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
          this.relativeHour = monthOrRelativeHour;
        }
      }
    }
    

    Source: http://mimosite.com/blog/post/2013/04/08/Overloading-in-TypeScript

提交回复
热议问题