In TypeScript, namespaces provide a way to logically group related code such as classes, interfaces, functions, and variables. They help in organizing code and avoiding naming conflicts.
What are Namespaces?
Namespaces in TypeScript are simply containers for organizing code. They are similar to modules but with some differences in how they are used.
Declaring a Namespace
To declare a namespace in TypeScript, you use the namespace
keyword followed by the namespace name.
namespace MyNamespace {
// Code inside the namespace
}
Accessing Members of a Namespace
To access members (such as classes, interfaces, functions, etc.) inside a namespace, you use the dot notation.
namespace MyNamespace {
export interface MyInterface {
// Interface members
}
}
let obj: MyNamespace.MyInterface;
Nested Namespaces
You can nest namespaces within other namespaces to further organize your code.
namespace OuterNamespace {
export namespace InnerNamespace {
// Code here
}
}
Using Namespaces in Files
You can split your code across multiple files using namespaces. To reference a namespace from another file, use the /// <reference>
directive.
/// <reference path="path-to-file.ts" />
namespace MyNamespace {
// Code here
}
Example: Using Namespaces
Let’s see a practical example of using namespaces in TypeScript.
// file1.ts
namespace Geometry {
export interface Shape {
calculateArea(): number;
}
}
// file2.ts
/// <reference path="file1.ts" />
namespace Geometry {
export class Circle implements Shape {
constructor(private radius: number) {}
calculateArea(): number {
return Math.PI * this.radius ** 2;
}
}
}
// main.ts
/// <reference path="file2.ts" />
let circle = new Geometry.Circle(5);
console.log(circle.calculateArea()); // Output: 78.53981633974483
Conclusion
Namespaces in TypeScript provide a way to organize code and prevent naming collisions. They are particularly useful for larger projects with multiple contributors. By using namespaces effectively, you can create more maintainable and scalable TypeScript applications.