繁体   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