簡體   English   中英

typescript重載類方法 - 返回類型相同,參數不同

[英]typescript overloading class methods - same return type, different parameters

我有一個打字稿類:

class ContactModel {

    public getUsage(type: string): restangular.IElement {
      return this.getBase().one('usages', type);
    }

    public getUsage(customerId: number, type: string): restangular.IElement {
      return this.ModelFactory.createRequestMapper(ContactModel.options)
        .one('customers', customerId).all('contacts/usages', type);
    }

    //...
}

這會導致編譯器拋出以下錯誤:

>> app/modules/common/model/ContactModel.ts(27,12): error TS2393: Duplicate function implementation.
>> app/modules/common/model/ContactModel.ts(31,12): error TS2393: Duplicate function implementation.

我在這個例子和TypeScript手冊之間看到的唯一區別是他們的例子有不同的返回類型,我有相同的返回類型(兩種情況都有不同的輸入參數)。

問題是:我做錯了什么 - 或者打字稿類方法是否需要使用不同的方法參數類型來允許重載? 這看起來很愚蠢,因為.Net和Java都支持使用相同的返回類型和不同的輸入類型進行重載。

JavaScript不會執行運行時類型信息,因此您必須自己進行過載消歧。 請注意,在手冊中的示例中,只有一個函數實現,而您有兩個。

class ContactModel {
  public getUsage(type: string): restangular.IElement;
  public getUsage(customerId: number, type: string): restangular.IElement;
  public getUsage(typeOrCustomerId: string|number, type?: string): restangular.IElement {
    if (typeof typeOrCustomerId === 'string') {
      // First overload
      return this.getBase().one('usages', type);
    } else {
      // Second overload
      return this.ModelFactory.createRequestMapper(ContactModel.options)
        .one('customers', customerId).all('contacts/usages', type);
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM