</>
Skip to content
TypeScript lessons (24/31)

TypeScript — Namespaces

Basic namespace

namespace Validation {
  export interface Validator {
    validate(value: string): boolean;
  }

  export class EmailValidator implements Validator {
    validate(value: string): boolean {
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
    }
  }
}

const validator = new Validation.EmailValidator();

Nested namespaces

namespace Shapes {
  export namespace Polygons {
    export class Triangle {}
    export class Square {}
  }
}

const triangle = new Shapes.Polygons.Triangle();

Aliases

import ShapeValidator = Validation.ShapeValidator;

When to use

  • Legacy codebases
  • Avoiding global pollution
  • Library organization

Modern alternative

// Prefer modules over namespaces
// modules/user.ts
export interface User {
  name: string;
}

// index.ts
import { User } from './modules/user';

Mini Practice

  1. Create namespace
  2. Export from namespace
  3. Use nested namespaces
  4. Compare with modules

Up Next

Continue with Ambient Declarations - Type declarations.

Related Topics

Frequently Asked Questions about Namespaces

What is Namespaces in TypeScript?

Namespaces is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Namespaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Namespaces.

Why is Namespaces important in TypeScript?

Namespaces is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.