【问题标题】:Implementing function overloading实现函数重载
【发布时间】:2013-02-28 20:57:48
【问题描述】:

由于 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");

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

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

【问题讨论】:

  • 你在我想说的翻译器中发现了一个错误。
  • 向接口添加功能的原因很清楚。这使我们能够(通过接口)描述 jquery 是如何工作的。但是我要如何在 typescript 中编写类似 jquery 的东西是我想要理解的。

标签: javascript typescript


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 2019-01-24
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多