TypeScript ยท Chapter 28 of 44

TypeScript Namespaces

Namespaces are an older TypeScript feature for grouping related code under a single named object, helping avoid naming collisions before ES modules were widely used.

Today, ES modules (with import/export) are generally preferred over namespaces for organizing code across files. However, you may still encounter namespaces in older codebases or certain declaration files.

Syntax
namespace Shapes {
  export function area(side: number): number {
    return side * side;
  }
}

Declaring a namespace

You group code with the `namespace` keyword, and export the members you want accessible from outside, such as `namespace Shapes { export function area() {} }`.

Namespaces vs modules

Modules (using import/export across files) are the modern standard for code organization. Namespaces are mostly seen in legacy code or type declaration files today.

Example 1 (typescript)
namespace Shapes {
  export function area(side: number): number {
    return side * side;
  }
}
console.log(Shapes.area(4));
Output
16

The area function is grouped inside the Shapes namespace and accessed with dot notation.

Example 2 (typescript)
namespace Utils {
  export const PI = 3.14;
  export function circleArea(r: number): number {
    return PI * r * r;
  }
}
console.log(Utils.circleArea(2));
Output
12.56

Both a constant and a function are grouped and exported from the Utils namespace.

Key points

  • Namespaces group related code under one named object.
  • Members must be marked `export` to be accessible outside the namespace.
  • ES modules are the modern, preferred way to organize code across files.
  • Namespaces are mostly found in legacy code and some declaration files.
๐Ÿ’ก Note: For new projects, prefer ES modules (import/export) over namespaces.

๐Ÿ“ Quick Quiz

1. What keyword declares a namespace?

2. What is the modern preferred alternative to namespaces?

3. What must namespace members have to be accessible outside it?