bf.v.rooyen
bf.v.rooyen

Reputation: 33

Typescript generating redundant variable

Consider the following Typescript code:

module demoAppModule{
    'use strict';

    export module nest{
        export var hello = function () {
            alert('Hello!');
        };
    }
}

demoAppModule.nest.hello();

After transpiling we have the following javascript code:

var demoAppModule;
(function (demoAppModule) {
    'use strict';

    (function (nest) {
        nest.hello = function () {
            alert('Hello!');
        };
    })(demoAppModule.nest || (demoAppModule.nest = {}));
    var nest = demoAppModule.nest;
})(demoAppModule || (demoAppModule = {}));

demoAppModule.nest.hello();

Why is this line generated? It hurts my eyes.

var nest = demoAppModule.nest;

Upvotes: 2

Views: 313

Answers (1)

basarat
basarat

Reputation: 276303

Short Answer: Its needed to access the module variable locally. E.g.

module demoAppModule{
    'use strict';

    export module nest{
        export var hello = function () {
            alert('Hello!');
        };
    }

    // The following would not be possible without that line 
    console.log(nest.hello);
}

demoAppModule.nest.hello();

Longer Answer: Its similar to the var added before a module e.g. notice var x:

// TypeScript 
module x{export var foo;}
// Generated JavaScript 
var x;
(function (x) {
    x.foo;
})(x || (x = {}));

But when you are inside a module + export a module the var needs to be added to outermodule.innermodule so you do not do var innermodule upfront. You add it to outermodule and then create a local variable to point to the innermodule which you can see in the generated javascript:

// Notice var here 
var demoAppModule;
(function (demoAppModule) {
    'use strict';

    // Notice no var here 
    (function (nest) {
        nest.hello = function () {
            alert('Hello!');
        };
    })(demoAppModule.nest || (demoAppModule.nest = {}));
    // Notice var assinged afterwards
    var nest = demoAppModule.nest;

    // The following would not be possible without that line
    console.log(nest.hello);
})(demoAppModule || (demoAppModule = {}));

demoAppModule.nest.hello();

Upvotes: 1

Related Questions