typescript overloading class methods - same return type, different parameters

后端 未结 1 1035
清歌不尽
清歌不尽 2021-02-19 19:53

I\'ve got a typescript class:

class ContactModel {

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


        
相关标签:
1条回答
  • 2021-02-19 20:55

    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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题