Javatpoint Logo
Javatpoint Logo

TypeScript Namespaces

The namespace is a way which is used for logical grouping of functionalities. It encapsulates the features and objects that share common relationships. It allows us to organize our code in a much cleaner way.

A namespace is also known as internal modules. A namespace can also include interfaces, classes, functions, and variables to support a group of related functionalities.

Unlike JavaScript, namespaces are inbuilt into TypeScript. In JavaScript, the variables declarations go into the global scope. If the multiple JavaScript files are used in the same project, then there will be a possibility of confusing new users by overwriting them with a similar name. Hence, the use of TypeScript namespace removes the naming collisions.

NOTE: A namespace can span in multiple files and allow to concatenate each file using "-outFile" as they were all defined in one place. It makes the code easier to maintain.

Namespace Declaration

We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces. We can declare the namespace as below.

To access the interfaces, classes, functions, and variables in another namespace, we can use the following syntax.

If the namespace is in separate TypeScript file, then it must be referenced by using triple-slash (///) reference syntax.

Example

The following program helps us to understand the use of namespaces.

Create Project and Declare files

NameSpace file: studentCalc

Main File: app.ts

Compiling and Executing Namespaces

Open the terminal and go to the location where you stored your project. Then, type the following command.

We will see the output below: studentCalc is not defined.

TypeScript Namespaces

So, the correct way to compile and execute the above code, we need to use the following command in the terminal window.

Now, we can see the following output.

TypeScript Namespaces

Nested Namespaces

A namespace also allows us to define one namespace into another namespace. We can access the members of the nested namespace by using the dot(.) operator. The following example helps us to understand the nested namespace more clearly.

Example

Nested NameSpace file: StoreCalc

Main File: app.ts

Now compile and execute the above code with the below command.

It produces the following output.

Output: 240
Next TopicTypeScript Module




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA