我有一个打字稿类:
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 Handbook之间看到的唯一区别是他们的例子有不同的返回类型,并且我有相同的返回类型(两种情况都有不同的输入参数).
问题是:我做错了什么 – 或者打字稿类方法是否需要使用不同的方法参数类型来允许重载?这看起来很愚蠢,因为.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',type);
}
}
}