TypeScript函数重载 [英] TypeScript function overloading

查看:108
本文介绍了TypeScript函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript语言规范的6.3节讨论了函数重载,并提供了有关如何实现此功能的具体示例.但是,如果我尝试这样的事情:

export class LayerFactory { 

    constructor (public styleFactory: Symbology.StyleFactory) { }

    createFeatureLayer (userContext : Model.UserContext, mapWrapperObj : MapWrapperBase) : any {           
         throw "not implemented";
    }                 

    createFeatureLayer(layerName : string, style : any) : any {
        throw "not implemented";
     }        

}

即使函数参数的类型不同,我也会收到指示重复标识符的编译器错误.即使我向第二个createFeatureLayer函数添加了一个附加参数,我仍然会遇到编译器错误.请提出想法.

解决方案

这可能是因为,当两个函数都编译为JavaScript时,它们的签名是完全相同的.由于JavaScript没有类型,因此我们最终创建了两个带有相同数量参数的函数.因此,TypeScript限制了我们创建此类功能.

TypeScript支持基于参数数量的重载,但是如果我们将其与OO语言进行比较,则遵循的步骤会有所不同.在回答另一个SO问题时,有人用一个很好的例子来解释它:方法重载了吗?. /p>

基本上,我们正在做的是,我们仅创建一个函数和许多声明,以使TypeScript不会产生编译错误.当此代码编译为JavaScript时,将仅显示具体功能.由于可以通过传递多个参数来调用JavaScript函数,因此它可以正常工作.

Section 6.3 of the TypeScript language spec talks about function overloading and gives concrete examples on how to implement this. However if I try something like this:

export class LayerFactory { 

    constructor (public styleFactory: Symbology.StyleFactory) { }

    createFeatureLayer (userContext : Model.UserContext, mapWrapperObj : MapWrapperBase) : any {           
         throw "not implemented";
    }                 

    createFeatureLayer(layerName : string, style : any) : any {
        throw "not implemented";
     }        

}

I get a compiler error indicating duplicate identifier even though function parameters are of different types. Even if I add an additional parameter to the second createFeatureLayer function, I still get a compiler error. Ideas, please.

解决方案

This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.

TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.

Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

这篇关于TypeScript函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆