In Typescript, namespaces are a way to organize code and avoid naming conflicts, especially when working with large codebases. It also allows us to organize our code in a much cleaner way.
Namespaces provide a mechanism for encapsulating elements and avoid polluting the global scope.
It's important to note that namespaces are different from modules, which offer more powerful and flexible ways to organize code.
A namespace can also include classes, variables (data), functions(methods), and interfaces to support various code-related functionalities.
Namespaces promote modularity by allowing us to split our code into smaller, reusable modules, which can be imported and used as needed.
namespace Namespace_Name { // methods, classes, interface and attributes can encapsulate export const attributeName: string = ""; export function functionName(): void {} export class NamespaceClass {} }
// NamespaceExample.ts namespace NamespaceExample { export const message: string = "This is a Sample Namespace Example"; export function showMessage(): void { console.log(message); //Output: "This is a Sample Namespace Example" } export class NamespaceClass { private value: number; constructor(value: number) { this.value = value; } getValue(): number { return this.value; } } } // Comment below code when testing with different file. const msg = NamespaceExample.message; console.log("Attribute Msg", msg); // Output: "Attribute Msg", "This is a Sample Namespace Example" NamespaceExample.showMessage(); const namespaceClassInstance = new NamespaceExample.NamespaceClass(1234); const value = namespaceClassInstance.getValue(); console.log("Attribute Value", value); // Output: "Attribute Value", 1234
NamespaceExample is a namespace that contains a constant (message), a function (showMessage), and a class (NamespaceClass).
The export keyword is used to make these elements accessible outside the namespace.
To access the namespace from another file, get its referenced by using triple-slash `///` reference syntax. Access namespace classes, functions, variables and interfaces by using dot `.` symbol.
/// <reference path="./NamespaceExample.ts" /> const msg = NamespaceExample.message; NamespaceExample.showMessage(); const namespaceClassInstance = new NamespaceExample.NamespaceClass(1234); const value = namespaceClassInstance.getValue();
NamespaceExample.AttributeName; NamespaceExample.MethodName; NamespaceExample.ClassName;
However, it's important to note that namespaces have some limitations and are considered an older way of organizing code.
Modern Typescript projects often use modules (via import and export statements) for better organization and to leverage features like ES6 modules.
Namespaces are still supported but are less commonly used in contemporary TypeScript development.