Functions Overloading in interface and classes - how to?
When you declare the function in the class you need to decorate it with the overloads:
getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
// your code
}
This answer describes how to implement method overloading in TypeScript, and it's not pretty:
interface IPoint {
getDist(): string;
getDist(x: number): any;
}
class Point implements IPoint {
// Constructor
constructor (public x: number, public y: number) { }
pointMethod() { }
getDist(x?: number) {
if (x && typeof x == "number") {
return 'foo';
} else {
return 'bar';
}
}
}
N.B. with the particular combination of declared return types in the interface, you are limited to returning strings from getDist
.