简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM