Constructor overload in TypeScript

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

    Regarding constructor overloads one good alternative would be to implement the additional overloads as static factory methods. I think its more readable and simple than checking for all possible argument combinations at the constructor. Here is a simple example:

    function calculateAge(birthday): number {
      return new Date().getFullYear() - birthday;
    }
    
    class Person {
      static fromData(data: PersonData): Person {
        const { first, last, birthday, gender = 'M' } = data;
        return new this(
          `${last}, ${first}`,
          calculateAge(birthday),
          gender,
        );
      }
    
      constructor(
        public fullName: string,
        public age: number,
        public gender: 'M' | 'F',
      ) {}
    
      toString(): string {
        return `Hello, my name is ${this.fullName} and I'm a ${this.age}yo ${this.gender}`;
      }
    }
    
    interface PersonData {
      first: string;
      last: string;
      birthday: string;
      gender?: 'M' | 'F';
    }
    
    
    const personA = new Person('Doe, John', 31, 'M');
    console.log(personA.toString());
    const personB = Person.fromData({
      first: 'Jane',
      last: 'Smith',
      birthday: '1986',
      gender: 'F',
    });
    console.log(personB.toString());
    

    Method overloading in TypeScript isn't for real, let's say, as it would require too much compiler-generated code and the core team try to avoid that at all costs. Currently the main reason for method overloading to be present on the language is to provide a way to write declarations for libraries with magic arguments in their API. Since you'll need to do all the heavy-lifting by yourself to handle different sets of arguments I don't see much advantage in using overloads instead of separated methods.

提交回复
热议问题