简体   繁体   中英

typescript overloading class methods - same return type, different parameters

I've got a typescript class:

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);
    }

    //...
}

which causes the compiler to throw following error:

>> 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.

The only difference I see between this example and the TypeScript Handbook is that their examples have different return types and I've got the same return types (both cases have different input parameters).

The question is: what am I doing wrong - or do typescript class methods need to have different method argument types to allow overloading? That seems stupid, since both .Net and Java support overloading with same return types and different input types.

JavaScript doesn't do runtime type information, so you have to do overload disambiguation yourself. Note that in the example in the Handbook, there's only one function implementation, whereas you have two.

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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM