namespace in typescript
In TypeScript, namespaces are a way to logically group related code together. They provide a way to organize code and prevent name collisions between identifiers (such as variables, functions, classes) that have the same name but serve different purposes in different parts of a program.
Declaring a Namespace
Namespaces are declared using the namespace
keyword in TypeScript. Here's a basic example:
namespace MyNamespace {
export const x = 10;
export function foo() {
return 'Hello, namespace!';
}
export interface Person {
name: string;
age: number;
}
}
In this example:
MyNamespace
is declared as a namespace using thenamespace
keyword.x
is a constant variable that is part ofMyNamespace
.foo()
is a function defined within the namespace.Person
is an interface defined within the namespace.
Accessing Members of a Namespace
To access members (variables, functions, interfaces, etc.) of a namespace outside of the namespace itself, you use the namespace name followed by a dot (.
) and then the member name:
console.log(MyNamespace.x); // Output: 10
let message = MyNamespace.foo();
console.log(message); // Output: Hello, namespace!
let person: MyNamespace.Person = {
name: 'Alice',
age: 30
};
console.log(person); // Output: { name: 'Alice', age: 30 }
Exporting from a Namespace
Members of a namespace can be explicitly marked for export using the export
keyword. This allows them to be accessed outside of the namespace when the namespace itself is imported:
namespace MyNamespace {
export const PI = 3.14;
export function calculateArea(radius: number): number {
return PI * radius * radius;
}
}
Nested Namespace
Namespaces can be nested within other namespaces to create a hierarchical organization of code:
namespace OuterNamespace {
export namespace InnerNamespace {
export const y = 20;
}
}
console.log(OuterNamespace.InnerNamespace.y); // Output: 20
When to Use Namespaces
Namespaces are primarily used to:
- Organize code into logical units to avoid naming collisions.
- Encapsulate functionality and data.
- Provide a structured way to manage large codebases.
- Group related interfaces, classes, functions, and constants.
However, with the advent of ECMAScript modules (ES modules) and TypeScript's ability to understand ES modules, namespaces are less commonly used in favor of ES module syntax (import
and export
statements) for organizing and structuring TypeScript code.