TypeScript Namespaces - TypeScript

How to define Namespace in Typescript?

A namespace is a logical grouping method. This is different from JavaScript, where variable declarations are global. If you use multiple JavaScript files in the same project, you might overwrite or misunderstand the same variable, which will lead to the "Global Namespace Pollution problem” in JavaScript.

Defining a Namespace

The namespace definition starts from the keyword namespace followed by the namespace name, as shown below:

  • The class or interface that should be accessed outside of the namespace should use the keyword export tag.
  • To access the class or interface in another namespace, the syntax will be namespaceName.className

If the first namespace is in a different TypeScript file, it must be referenced using a triple-slash reference syntax.

The following program demonstrates use of namespaces

The above code can be compiled and executed using the following command

At compile time, it will generate the following JavaScript code (app.js).

When compiling and executing the above code, the following results are produced

Nested Namespaces

You can define one namespace inside another namespace as follows

The dot (.) Operator is used to access members of the nested namespace, as shown below

The above code can be compiled and executed using the following command

At compile time, it will generate the following JavaScript code (app.js).

When compiling and executing the above code, the following results are produced

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

TypeScript Topics