The TypeScript scripts written by default are in the global scope which means that all the functions, methods, variables, etc. in one file are accessible in all other TypeScript files. This can lead to conflicts in variables, functions as programmers can edit the function/variable name or value without any realization. Therefore, the concept of modules was introduced to prevent this default global scope and instead wrap all associated variables and functions in the local scope. This is useful, especially when maintaining a huge codebase.
Since modules create local scopes in the TypeScript file, all variables, functions, or classes defined in a module would not be accessible outside of that particular module. In this article, we will see how to allow classes defined in a module to be accessible outside of the module. The syntax for a class defined in a module in TypeScript is as follows:
Syntax:
module nameOfModule { class nameOfClass { field; method; } }
Example 1: In this example, a class of Students is created inside a module named University which has a parameterized constructor used for initialization or construction of objects with the parameters of a string representing the name of the student and a number representing the age of the student.
script.ts
module University { class Student { constructor(public name: string, public age: number) { } } var firstStudent = new Student( "neveropen" , 15); } var secondStudent = new University.Student( "Rajat" , 20); console.log(secondStudent); |
Output: There is a compilation error as the class Student inside the University module is not accessible outside of the module as discussed earlier.
To combat this, we simply use the export keyword which makes all classes or functions, variables, methods inside a module accessible outside of that module. In other words, we can say that the export keyword converts all local scoped classes or functions, variables into the global scope.
Example 2: This example is very similar to the previous example but the only distinction is that the export keyword is used before the class Student which means that the class and its associated functions, methods can be utilized outside of the University module.
index.ts
module University { export class Student { constructor(public name: string, public age: number) { } } var firstStudent = new Student( "neveropen" , 15); } var secondStudent = new University.Student( "Rajat" , 20); console.log(secondStudent); |
index.js
var University; ( function (University) { var Student = /** @class */ ( function () { function Student(name, age) { this .name = name; this .age = age; } return Student; }()); University.Student = Student; var firstStudent = new Student( "neveropen" , 15); })(University || (University = {})); var secondStudent = new University.Student( "Rajat" , 20); console.log(secondStudent); |
Output: