I'm trying to overload a method using Typescript. It seems like the usual way of overloading in Java or C# doesn't apply for Typescript. I can't do this:
public sayHello(): string {
var partialMessage = this.fullName + " says hello to ";
return partialMessage + "Unknown";
}
public sayHello(name: string) {
var partialMessage = this.fullName + " says hello to ";
return partialMessage + obj;
}
I searched around and figured out that I have to do it this way:
public sayHello():string;
public sayHello(name: string):string;
public sayHello(person:Person):string;
public sayHello(obj?: any) {
var partialMessage = this.fullName + " says hello to ";
if(typeof obj === "string") {
return partialMessage + obj;
} else if(obj instanceof Person) {
return partialMessage + (<Person>obj).fullName;
} else {
return partialMessage + "Unknown";
}
}
This method seems quite untidy and difficult to maintain to me because I'm cluttering everything into a single method and dividing the logic using if/else statements.
Is there a better way I can do method overloading in Typescript?