Namespaces are a way to organize and group our code into logical modules to avoid name collisions between different parts of our program.
A namespace in TypeScript encapsulates variables, functions, classes, and other elements within a container. This allows us to group and organize our code, avoiding conflicts and improving its readability and maintainability.
To define a namespace in TypeScript, we use the keyword namespace followed by the name we want to assign to the namespace. For example:
namespace MyNamespace {
export function greet() {
console.log("Hello from MyNamespace!");
}
}
In this example,
- We create a namespace called
MyNamespace - It contains a function
greet. - The
exportdeclaration allows the function to be accessible outside the namespace.
Using Namespaces
Once we have defined a namespace, we can use it in other parts of our program. To access elements within a namespace, we use the syntax NamespaceName.ElementName. For example:
MyNamespace.greet();
In this case, we are calling the greet function that resides inside the MyNamespace namespace.
Nesting Namespaces
In TypeScript, it is also possible to nest namespaces inside other namespaces. This allows us to organize our code even further and avoid name collisions. For example:
namespace MyNamespace {
export namespace SubNamespace {
export function sayGoodbye() {
console.log("Goodbye from SubNamespace!");
}
}
}
In this case,
- We have nested a namespace called
SubNamespaceinside theMyNamespacenamespace - The
sayGoodbyefunction is inside theSubNamespacenamespace - To access this function, we use the syntax
MyNamespace.SubNamespace.sayGoodbye()
