TypeScript Constructor Overload with Empty Constructor

前端 未结 4 1883
春和景丽
春和景丽 2020-12-15 03:30

Why is it not allowed to have separate constructor definitions in TypeScript?
To have e.g. two constructors<

4条回答
  •  情深已故
    2020-12-15 04:17

    You can use Builder pattern to solve this. Even in C# or Python, it quickly becomes a better approach as the number of constructor arguments grows.

    class Foo {
      constructor(public id: number, public name: string, public surname: string, public email: string) {
      }
      static Builder = class {
        id: number = NaN;
        name: string = null;
        surname: string = null;
        email: string = null;
        Builder() {
        }
        build(): Foo {
          return new Foo(this.id, this.name, this.surname, this.email);
        }
      }
    }
    

提交回复
热议问题