Google News
logo
TypeScript - Interview Questions
What are the Modules in Typescript?
A module is a powerful way to create a group of related variables, functions, classes, and interfaces, etc. It can be executed within their own scope, not in the global scope. In other words, the variables, functions, classes, and interfaces declared in a module cannot be accessible outside the module directly.
 
Creating a Module
 
A module can be created by using the export keyword and can be used in other modules by using the import keyword.
module module_name{  
    class xyz{  
        export sum(x, y){  
            return x+y;  
         }  
    } ​
We can divide the module into two categories :
 
* Internal Module
* External Module
 
Internal Module : Internal modules were in the earlier version of Typescript. It was used for logical grouping of the classes, interfaces, functions, variables into a single unit and can be exported in another module. The modules are named as a namespace in the latest version of TypeScript. So today, internal modules are obsolete. But they are still supported by using namespace over internal modules.
 
Syntax :
module Sum {   
   export function add(a, b) {    
      console.log("Sum: " +(a+b));   
   }   
} ​

 

External Module : External modules are also known as a module. When the applications consisting of hundreds of files, then it is almost impossible to handle these files without a modular approach. External Module is used to specify the load dependencies between the multiple external js files. If the application has only one js file, the external module is not relevant. ECMAScript 2015(ES6) module system treats every file as a module.

Syntax :
export class MyClass {
}
export var x:MyClass instance = new MyClass();
Advertisement