Javatpoint Logo
Javatpoint Logo

TypeScript Namespaces

A namespace is a way that is used for logical grouping of functionalities. It encapsulates the features and objects that share certain relationships. It will help 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, and if multiple JavaScript files are used in the same project, then there will be a possibility of confusing new users by overloading them with similar named. Hence, the use of TypeScript namespace removes the naming collisions.

NOTE: A namespace can be defined in multiple files and allow to keep each file as they were all defined in one place. It makes code easier to maintain.

Namespace Declaration

A namespace definition can be created 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. The declaration of a namespace is given below.

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

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


The following program help to understands 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 compiled and executed the above code by the following command.

We will see the following output.

TypeScript Namespaces

Nested Namespaces

We can also define one namespace into another namespace. We can access the members of the nested namespace by using the dot(.) operator. It can be shown as below.


Nested NameSpace file: StoreCalc

Main File: app.ts

Now compiled and executed the above code, we will get the following output.

Next TopicTypeScript Module

Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA