w3resource

TypeScript Nested Namespaces

TypeScript Modules and Namespaces : Exercise-7 with Solution

Create a TypeScript namespace called Geometry and nest two sub-namespaces within it: Shapes and Utilities. Define classes for different geometric shapes (e.g., Circle, Rectangle) inside the Shapes namespace and utility functions (e.g., calculateArea, calculatePerimeter) inside the Utilities namespace. Demonstrate how to access these namespaces and use their contents.

Sample Solution:

TypeScript Code:

main.ts

import Geometry from './Geometry';

const circle = new Geometry.Shapes.Circle(6);
console.log('Circle Area: ${circle.calculateArea()}'); 

const rectangle = new Geometry.Shapes.Rectangle(12, 10);
console.log('Rectangle Area: ${Geometry.Utilities.calculateArea(rectangle)}'); 
console.log('Rectangle Perimeter: ${Geometry.Utilities.calculatePerimeter(rectangle)}'  

Geometry.ts

namespace Geometry {
  export namespace Shapes {
    export class Circle {
      constructor(public radius: number) {}

      calculateArea(): number {
        return Math.PI * this.radius * this.radius;
      }
    }

    export class Rectangle {
      constructor(public width: number, public height: number) {}

      calculateArea(): number {
        return this.width * this.height;
      }

      calculatePerimeter(): number {
        return 2 * (this.width + this.height);
      }
    }
  }

  export namespace Utilities {
    export function calculatePerimeter(shape: Shapes.Rectangle): number {
      return shape.calculatePerimeter();
    }

    export function calculateArea(shape: Shapes.Circle | Shapes.Rectangle): number {
      return shape.calculateArea();
    }
  }
}
export default Geometry;

Explanation:

In the exercise above -

  • "Geometry.ts" is a TypeScript namespace with two sub-namespaces: 'Shapes' and 'Utilities'. Inside the "Shapes" namespace, we define classes for geometric shapes (Circle and Rectangle), each with methods for calculating their areas and perimeters. Inside the "Utilities" namespace, we define utility functions for calculating shapes' area and perimeter.
  • In "main.ts", we import the "Geometry" namespace using the 'import' statement.
  • Finally we create instances of the "Circle" and "Rectangle" classes and use "utility ()" functions to calculate the rectangle's area and perimeter.

Output:

Circle Area: 113.09733552923255
Rectangle Area: 120
Rectangle Perimeter: 44

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Basic Namespace.
Next: Exporting Namespace Content in TypeScript.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.