简体   繁体   English

typescript重载类方法 - 返回类型相同,参数不同

[英]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). 我在这个例子和TypeScript手册之间看到的唯一区别是他们的例子有不同的返回类型,我有相同的返回类型(两种情况都有不同的输入参数)。

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. 这看起来很愚蠢,因为.Net和Java都支持使用相同的返回类型和不同的输入类型进行重载。

JavaScript doesn't do runtime type information, so you have to do overload disambiguation yourself. JavaScript不会执行运行时类型信息,因此您必须自己进行过载消歧。 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);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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