Typescript namespace
Created By: chatGPT
Namespaces in TypeScript are a way to group related code together, making it easier to manage and avoid name conflicts. They are similar to modules, but are primarily used in scenarios where ES6 module support is not available or needed. You can define a namespace using the
namespace
keyword. Here's an example to demonstrate its use:namespace Geometry {
export class Circle {
constructor(public radius: number) {}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
export class Rectangle {
constructor(public width: number, public height: number) {}
area(): number {
return this.width * this.height;
}
}
}
In this example, we have a Geometry namespace containing two classes: Circle and Rectangle. By using the
export
keyword, we make these classes accessible from outside the namespace. Here's how you can use these classes:const circle = new Geometry.Circle(10);
console.log(`Circle area: ${circle.area()}`);
const rectangle = new Geometry.Rectangle(10, 5);
console.log(`Rectangle area: ${rectangle.area()}`);
You can also have nested namespaces, which allows you to further organize your code. Here's an example with a nested namespace:
namespace Shapes {
export namespace Polygons {
export class Triangle {
constructor(public base: number, public height: number) {}
area(): number {
return 0.5 * this.base * this.height;
}
}
}
}
You can access the Triangle class inside the Polygons namespace like this:
Namespaces are often preferred in older TypeScript projects or those that need to support legacy JavaScript environments. However, modern TypeScript typically favors ES6 module syntax for a more straightforward approach to organizing code. Always consider the project's requirements when choosing between namespaces and modules.const triangle = new Shapes.Polygons.Triangle(10, 5);
console.log(`Triangle area: ${triangle.area()}`);