1

由于 javascript 不支持函数重载 typescript 不支持它。然而,这是一个有效的接口声明:

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

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

但是我怎样才能实现这个接口。打字稿不允许此代码:

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

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

    }
    test(x:number){

    }
}

尝试一下

4

1 回答 1

5

Typescript 中的函数重载是这样完成的:

class foo implements IFoo {
    test(x: string);
    test(x: number);
    test(x: any) {
        if (typeof x === "string") {
            //string code
        } else {
            //number code
        }
    }
}
于 2013-03-13T03:54:34.930 回答