Search code examples
typescriptreactjs-fluxflux

Can TypeScript exports be overloaded?


I found some weird typescript syntax in looking at flux, that isn't making any sense. For example;

class Action {
    private _source: Action.Source

    constructor( source: Action.Source ) {
        this._source = source
    }

    get source() {
        return this._source
    }
}

module Action {
    export enum Source {
        View,
        Server
    }
}

export = Action

What exactly does export = Action do here? Is it being overloaded to export the module and the class? Mixing them somehow? I'm not understanding the semantics here..


Solution

  • It's using declaration merging. What is happening behind the scenes is essentially something like this:

    // class is defined
    function Action(source) {
        this._source = source;
    }
    
    Object.defineProperty(Action.prototype, "source", {
        get: function () {
            return this._source;
        },
        enumerable: true,
        configurable: true
    });
    
    // enum is defined on the Source property of Action—NOT on Action's prototype
    Action.Source = ...enum object definition...
    
    export = Action;
    

    Read more about "Merging Modules with Classes, Functions, and Enums" in the Handbook.