Namespaces in TypeScript

1. Welcome and Icebreaker:

  • If you could group any set of things in your life under a single name, what would you group?

2. Outline the Session:

  • We’ll learn about namespaces in TypeScript: how to group related code together.
  • Learning Outcomes: Understand how to use namespaces and when to prefer modules instead.
  • Let’s organize our code!

3. Concept Explanation:

  • Namespaces are a way to group related code under a single name, avoiding name collisions.
  • Use the namespace keyword. Namespaces are mostly used in legacy code; prefer ES modules for new projects.
  • Syntax:
    namespace MathUtils {
      export function add(a: number, b: number): number {
        return a + b;
      }
    }
    console.log(MathUtils.add(2, 3));
    
  • Namespaces can be split across multiple files using /// <reference path="..." /> (not recommended for modern projects).

4. Live Coding Demonstration:

namespace Geometry {
  export function areaOfCircle(radius: number): number {
    return Math.PI * radius * radius;
  }
  export function areaOfSquare(side: number): number {
    return side * side;
  }
}
console.log(Geometry.areaOfCircle(3));
console.log(Geometry.areaOfSquare(4));

5. Tasks:

  • Short Exercise:
    1. Create a namespace Utils with two functions: capitalize (string) and reverse (string).
    2. Use both functions in your code.
    3. Try splitting a namespace across two files (using /// <reference path=... />).