basarat
basarat

Reputation: 275857

Implementing function overloading

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

Upvotes: 1

Views: 134

Answers (1)

GJK
GJK

Reputation: 37369

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
        }
    }
}

Upvotes: 5

Related Questions