2013-03-13 72 views
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){ 

    } 
} 

Try it

+0

你已经发现,在翻译我想说的错误。 – kay 2013-03-13 03:37:43

+0

为接口添加功能的原因很明显。这允许我们描述(通过接口)jQuery如何工作。但是我如何在打字稿中写jQuery这样的东西正是我想要理解的。 – basarat 2013-03-13 03:52:47

回答

5

功能的打字稿超载像这样做:

class foo implements IFoo { 
    test(x: string); 
    test(x: number); 
    test(x: any) { 
     if (typeof x === "string") { 
      //string code 
     } else { 
      //number code 
     } 
    } 
}