Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Namespaces

Namespaces help organize related classes, interfaces, functions, and variables under a common name. They are useful for grouping code and avoiding naming conflicts.

Learning objective: Understand namespace syntax, exported members, nested namespaces, namespace aliases, and how namespaces can be used across multiple files.

1. What Is a Namespace?

A namespace is a named container that groups related code together. In TypeScript, the namespace keyword is used to define a namespace.

For example, an application may contain separate modules for students, employees, and payments. Namespaces can group related types and functions under names such as StudentManagement or PaymentManagement.

🎓
StudentManagement

Student class, student interface, student functions

👨‍💻
EmployeeManagement

Employee class, employee interface, employee functions

💳
PaymentManagement

Payment types, payment functions, payment-related logic

Remember: Namespaces group code under a common name. They are different from ES modules, which organize code using import and export statements.

2. Namespace Syntax

Define a namespace using the namespace keyword followed by its name and a pair of braces.

namespace StudentManagement {
    export class Student {
        name: string;

        constructor(name: string) {
            this.name = name;
        }

        display(): void {
            console.log("Student Name: " + this.name);
        }
    }
}

const student = new StudentManagement.Student("Rahul");
student.display();

Expected Output

Student Name: Rahul

How It Works

  1. namespace StudentManagement creates the namespace.
  2. export class Student makes the class available outside the namespace.
  3. new StudentManagement.Student("Rahul") accesses the class through its namespace.
  4. display() prints the student name.

3. Export Members from a Namespace

Members declared inside a namespace are not automatically accessible from outside it. Use the export keyword when a member needs to be accessed externally.

Exported Member
namespace MathTools {
    export function add(
        a: number,
        b: number
    ): number {
        return a + b;
    }
}

console.log(MathTools.add(10, 20));

Output: 30

Non-exported Member
namespace MathTools {
    function multiply(
        a: number,
        b: number
    ): number {
        return a * b;
    }
}

// This cannot access the
// non-exported member externally:
// MathTools.multiply(2, 3);

The multiply function is accessible within its namespace, but not as MathTools.multiply() outside it.

Important: export inside a namespace exposes a namespace member. It is not the same as the ES module export statement used in a module file.

4. Namespace with Interfaces and Functions

A namespace can contain multiple related types and functions. This is useful when a group of features belongs to the same application area.

namespace EmployeeManagement {
    export interface Employee {
        id: number;
        name: string;
        salary: number;
    }

    export function displayEmployee(
        employee: Employee
    ): void {
        console.log("ID: " + employee.id);
        console.log("Name: " + employee.name);
        console.log("Salary: " + employee.salary);
    }
}

const employee: EmployeeManagement.Employee = {
    id: 101,
    name: "Priya",
    salary: 40000
};

EmployeeManagement.displayEmployee(employee);

Expected Output

ID: 101
Name: Priya
Salary: 40000

Here, both Employee and displayEmployee are exported, so they can be accessed using EmployeeManagement.

5. Nested Namespaces

A namespace can be declared inside another namespace. This is called a nested namespace and can help organize related sub-features.

namespace Company {
    export namespace HR {
        export function showDepartment(): void {
            console.log("Human Resources Department");
        }
    }
}

Company.HR.showDepartment();

Expected Output

Human Resources Department
How to access it: Company.HR.showDepartment() uses the outer namespace, the inner namespace, and then the exported function.

6. Namespace Alias

When a namespace name is long, you can create an alias using the import alias syntax. This is a TypeScript namespace-alias feature, not an ES module import statement.

namespace Application {
    export namespace StudentManagement {
        export function getMessage(): string {
            return "Welcome to Student Management";
        }
    }
}

import StudentApp = Application.StudentManagement;

console.log(StudentApp.getMessage());

Expected Output

Welcome to Student Management

The alias StudentApp refers to Application.StudentManagement, making the access shorter.

7. Namespaces Across Multiple Files

In a traditional TypeScript namespace setup, related declarations can be placed in multiple files. A reference directive can tell the compiler about a dependent file.

File 1: Validation.ts

namespace Validation {
    export function isValidEmail(
        email: string
    ): boolean {
        return email.includes("@");
    }
}

File 2: App.ts

/// <reference path="Validation.ts" />

console.log(
    Validation.isValidEmail("student@example.com")
);

Compile the Files

tsc App.ts --outFile app.js

Expected Output

true
Note: The /// <reference path="Validation.ts" /> directive helps the TypeScript compiler include the referenced file. The output-file approach is intended for compatible non-module scripts. In modern applications, separate ES modules with import and export are generally preferred.

8. Namespace vs ES Modules

Feature Namespace ES Module
Declaration namespace MyApp export and import
Code organization Groups code under a namespace name Organizes code into separate module files
Accessing members MyApp.myFunction() Import the required member or module
File behavior Often used with non-module scripts Uses module loading and module scope
Typical use Existing namespace-based code or specific script setups Most modern TypeScript applications
Industry tip: For a new ASP.NET Core front-end or modern TypeScript project, learn ES modules first. Understand namespaces as well because they may appear in existing projects and legacy code.

9. Common Mistakes

Forgetting export

A member without export cannot be accessed through the namespace from outside it.

Using the wrong name

Namespace names are case-sensitive. Use the same spelling and casing when accessing members.

Confusing namespace and module imports

import Alias = MyNamespace is a namespace alias pattern; it is not the same as importing from another module file.

Using namespaces for every new project

Modern TypeScript projects generally organize files using ES modules. Choose the approach appropriate to your project.

Summary

  • The namespace keyword groups related TypeScript code.
  • The export keyword exposes namespace members outside the namespace.
  • Namespaces can contain classes, interfaces, functions, and nested namespaces.
  • Namespace aliases can shorten references to long namespace names.
  • Reference directives can connect files in traditional namespace-based projects.
  • ES modules using import and export are generally preferred for modern applications.