Search code examples
typescriptoverloading

TypeScript function overloading


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) {
        // Init...
    }
    createFeatureLayer(userContext: Model.UserContext, mapWrapperObj: MapWrapperBase): any {           
        throw new Error('not implemented');
    }
    createFeatureLayer(layerName: string, style: any): any {
        throw new Error('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.


Solution

  • This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, the only option is to create a single functions with a dynamic number of arguments. So TypeScript will let you declare multiple function signatures, but it will not let you implement multiple versions of the same function.

    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: How to do method overloading in TypeScript?.

    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.