-1

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?

Carven
  • 14,988
  • 29
  • 118
  • 161
  • @WiredPrairie I know how to overload a method in Typescript. In fact, I had shown how I can do that in my question. My question was whether or not there is a better way to do this in Typescript. I'm just not sure if I'm missing out anything because the way to overload a method in TS seems inconvenient to me. – Carven Feb 20 '14 at 16:30
  • I'd still suggest that it's the same answer, and the question is just asked in a slightly different way. – WiredPrairie Feb 20 '14 at 17:10

1 Answers1

0

You have to use the second form. JavaScript has no type checking on function arguments or even the number of arguments. Only one version of a function can exist with a given name. So when the TypeScript compiles to JavaScript it can only create a single function for a given method.

See

Gerard Condon
  • 761
  • 1
  • 7
  • 22