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.
No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.
You cannot overload function declarations that differ only by return type. The function overloading is basically the compile time polymorphism. It checks the function signature.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With