TypeScript 函数重载 [英] TypeScript function overloading

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

问题描述

TypeScript 语言规范的第 6.3 节讨论了函数重载,并给出了如何实现这一点的具体示例.但是,如果我尝试这样的事情:

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

}

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

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.

推荐答案

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

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 支持基于参数数量的重载,但如果我们与面向对象的语言相比,要遵循的步骤有点不同.在回答另一个 SO 问题时,有人用一个很好的例子解释了它:方法重载?.

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?.

基本上,我们正在做的是,我们只创建一个函数和许多声明,以便 TypeScript 不会出现编译错误.当这段代码被编译成 JavaScript 时,具体的功能就会单独显示出来.由于可以通过传递多个参数来调用 JavaScript 函数,因此它可以正常工作.

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天全站免登陆