Use of Modules in TypeScript

Modules in TypeScript

 
Modules are another feature of TypeScript. TypeScript allows encapsulation of implementation in classes at design time with the ability to restrict the 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.
 
Syntax
  1. 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.
  
ExampleOfModules.ts
  1. module Mcn {  
  2.  var message = "Welcome in Mcn Solution !";  
  3.  exportfunction CompName() {  
  4.   document.write(message);  
  5.  }  
  6. }  
  7. Mcn.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.
 
default.html
  1. <!DOCTYPEhtml>  
  2. <htmllang="en"  
  3.     xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <metacharset="utf-8"/>  
  6.         <title>TypeScript Modules</title>  
  7.         <linkrel="stylesheet"href="app.css"type="text/css"/>  
  8.         <scriptsrc="app.js">  
  9.         </script>  
  10.     </head>  
  11.     <body>  
  12.         <divid="content"/>  
  13.     </body>  
  14. </html>  
app.js
  1. var Mcn;  
  2. (function(Mcn) {  
  3.  var message = "Welcome in Mcn Solution !";  
  4.   
  5.  function CompName() {  
  6.   document.write(message);  
  7.  }  
  8.  Mcn.CompName = CompName;  
  9. })(Mcn || (Mcn = {}));  
  10. Mcn.CompName();  
Step 4
 
Output
 
module-in-TypeScript.jpg 


Similar Articles