TypeScriptModules and namespaces
Nested namespaces in TypeScript
7 A Geometry namespace with two nested inside it
fairWrite a namespace called Geometry containing two nested namespaces: one holding shape classes and one holding utility functions. Show how to reach into both.
Stuck? Three hints, smallest first
- 1. Nest by writing
export namespace Shapes { ... }inside the outer one. - 2. Every level you want reachable from outside needs its own
export. - 3. An alias shortens a long path:
import S = Geometry.Shapes;— legal inside a namespace context.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
namespace Geometry {
export namespace Shapes {
export class Circle {
constructor(public radius: number) {}
}
export class Rectangle {
constructor(public width: number, public height: number) {}
}
}
export namespace Utilities {
export function calculateArea(shape: Shapes.Circle | Shapes.Rectangle): number {
return shape instanceof Shapes.Circle
? Math.PI * shape.radius ** 2
: shape.width * shape.height;
}
export function calculatePerimeter(shape: Shapes.Circle | Shapes.Rectangle): number {
return shape instanceof Shapes.Circle
? 2 * Math.PI * shape.radius
: 2 * (shape.width + shape.height);
}
}
}
// The full path works...
const circle = new Geometry.Shapes.Circle(2);
const rect = new Geometry.Shapes.Rectangle(3, 4);
console.log(Geometry.Utilities.calculateArea(circle).toFixed(2));
console.log(Geometry.Utilities.calculateArea(rect));
// ...and an alias keeps it readable when the path gets long.
const Shapes = Geometry.Shapes;
const Utils = Geometry.Utilities;
const square = new Shapes.Rectangle(5, 5);
console.log('square area:', Utils.calculateArea(square));
console.log('square perimeter:', Utils.calculatePerimeter(square));
test('circle area', Number(Utils.calculateArea(circle).toFixed(2)), 12.57);
test('rectangle area', Utils.calculateArea(rect), 12);
test('circle perimeter', Number(Utils.calculatePerimeter(circle).toFixed(2)), 12.57);
test('rectangle perimeter', Utils.calculatePerimeter(rect), 14);
test('the alias points at the same class', square instanceof Geometry.Shapes.Rectangle, true);
test('square area via the alias', Utils.calculateArea(square), 25);
Output
Geometry.Utilities.calculateArea(...) is the argument against deep nesting all by itself. Note that the utilities refer to Shapes.Circle without the Geometry. prefix, because inside the outer namespace the sibling is already in scope. Also notice the circle’s area and perimeter are both 12.57 at radius 2 — a coincidence, not a bug.