1

Since javascript does not support function overloading typescript does not support it. However this is a valid interface declaration:

// function overloading only in the interface 
interface IFoo{
    test(x:string);
    test(x:number);
}

var x:IFoo;
x.test(1);
x.test("asdf");

But how can I implement this interface. Typescript does not allow this code:

// function overloading only in the interface 
interface IFoo{
    test(x:string);
    test(x:number);
}

class foo implements IFoo{
    test(x:string){

    }
    test(x:number){

    }
}

Try it

3
  • You have found a bug in the translator I'd say. Commented Mar 13, 2013 at 3:37
  • The reason for adding the functionality to interfaces is quite clear. This is what allows us to describe (via interfaces) how jquery works. But how I would write something like jquery in typescript is what I am trying to understand. Commented Mar 13, 2013 at 3:52
  • Does this answer your question? TypeScript function overloading Commented Sep 4, 2023 at 14:06

1 Answer 1

5

Function overloading in Typescript is done like this:

class foo implements IFoo {
    test(x: string);
    test(x: number);
    test(x: any) {
        if (typeof x === "string") {
            //string code
        } else {
            //number code
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.