2

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;
1
  • That line seems completely useless to me. The only reason I can think of is that the compiler thinks that the parameter nest must be defined before the function hello, however the assignment takes place at the very bottom and then does nothing with it. Commented Aug 26, 2013 at 7:19

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Reading this I realize that had I used nest afterwards, like the logging in your example, it wouldn't have looked so unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.