← Back to TypeScript Course | Chapter 9: Modules and Namespaces | Lesson 4 of 7

Namespace Basics

A namespace groups related TypeScript declarations under a single name. Namespaces are mainly useful for organizing code within a global or legacy-style codebase, while modern projects generally prefer ES modules.

Creating a Namespace

Use the namespace keyword to create a named container for related declarations, grouping them under a single accessible name without needing separate files or an ES module system.

Example: Creating a Namespace

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

Exporting Namespace Members

Members inside a namespace must be exported from it if code outside the namespace needs to access them, mirroring how modules control what's visible outside their own boundary.

Example: Exporting Namespace Members

typescript
namespace MathUtils {
  export const PI = 3.14159;
  function internalHelper() { return "hidden"; }
}
console.log(MathUtils.PI);

Nested Namespaces

Namespaces can contain other namespaces, nesting related declarations into deeper, more specific groupings, similar to how packages can be nested inside other packages. Deeply nested namespaces are accessed with dotted paths, like Outer.Inner.member.

Example: Nested Namespaces

typescript
namespace Outer {
  export namespace Inner {
    export const value = 42;
  }
}
console.log(Outer.Inner.value);

Namespaces with Classes

Classes can be exported from namespaces and then accessed through the namespace name, letting a namespace bundle related classes, interfaces, and functions together under one umbrella.

Example: Namespaces with Classes

typescript
namespace Shapes {
  export class Circle {
    constructor(public radius: number) {}
  }
}
const c = new Shapes.Circle(5);
console.log(c.radius);

Namespaces and Modern Modules

Namespaces are an older TypeScript organization mechanism that predates widespread ES module support; for modern applications, ES modules are the recommended way to organize code instead.

Example: Namespaces and Modern Modules

typescript
// Older style:
namespace Legacy {
  export const value = 1;
}
// Modern style (recommended):
// export const value = 1;
console.log(Legacy.value);
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.