Use of Modules in TypeScript

Modules in TypeScript

Modules is another feature of TypeScript. TypeScript allows encapsulation of implementation in classes at design time with the ability to restrict use of private members, but cannot allow encapsulation at runtime because all object properties are accessible at runtime. In JavaScript, the only way to allow encapsulation at runtime is to use the module pattern, and if  you want to allow encapsulation of implementation in classes at runtime time with the use of private members, then you can also use modules in TypeScript. TypeScript also supports external modules, which are files that contain top-level export and import directives.


module moduleName {//............body}

Step 1

Open Visual Studio 2012 and click on "File" menu -> "New" -> "Project". A window will be opened. Provide the name of  your application like "ExampleOfModules", then click on the Ok button.

Step 2

After Step 1 your project has been created. Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, css file and html files.

Step 3

The code of the Modules program follows.


module Mcn {

    var message = "Welcome in Mcn Solution !";

    exportfunction CompName()






Note In the above declared program, the variable "
message" is a private feature of the module, but the function "CompName" is exported from the module and accessible to code outside of the module.








    <title>TypeScript Modules</title>









var Mcn;

(function (Mcn) {

    var message = "Welcome in Mcn Solution !";

    function CompName() {



    Mcn.CompName = CompName;

})(Mcn || (Mcn = {}));


Step 4



Up Next
    Ebook Download
    View all


    Read by 16 people
    Download Now!
    View all