Open In App

What is namespace in Typescript ?

In this article, we are going to see what is namespace in Typescript. In TypeScript, a namespace is a way to organize code into logical groups and avoid naming collisions between identifiers. Namespaces provide a way to group related code into a single namespace or module so that we can manage, reuse and maintain our code easily.

Benefits of Using Namespaces:



How to declare Namespace: In the code snippet written below, we have declared a namespace called MyNamespace. We have also defined a function called myFunction inside the namespace. The export keyword is used to make the function accessible outside the namespace.

namespace MyNamespace {
    export function myFunction() {
        console.log('This is my function');
    }
}

How to Access the Namespace: To access a function inside a namespace, you can use the dot notation to specify the namespace and function name. in the code below we can see that. we are accessing the myFunction function inside the MyNamespace namespace.



MyNamespace.myFunction(); // Output: This is my function

Example 1: In this example, we have created a simple namespace called MyNamespace with a single function called myFunction. We have also used the export keyword to make the function accessible outside the namespace. Finally, we have called the myFunction function outside the namespace using the dot notation.




namespace MyNamespace {
    export function myFunction() {
        console.log('This is my function in MyNamespace');
    }
}
  
// Output: This is my function in MyNamespace
MyNamespace.myFunction();

Output:

"This is my function in MyNamespace" 

Example 2: In this example, we have created a nested namespace called MySubNamespace inside the MyNamespace namespace. We have also defined a function called myFunction inside the MySubNamespace namespace. We have used the export keyword to make the function accessible outside the namespace. Finally, we have called the myFunction function outside the namespace using the dot notation with both the parent and child namespace names.




namespace MyNamespace {
    export namespace MySubNamespace {
        export function myFunction() {
            console.log('This is my function in MySubNamespace');
        }
    }
}
  
// Output: This is my function in MySubNamespace
MyNamespace.MySubNamespace.myFunction();

Output: 

"This is my function in MySubNamespace" 

Article Tags :