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.
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
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
namespace StudentManagementcreates the namespace.export class Studentmakes the class available outside the namespace.new StudentManagement.Student("Rahul")accesses the class through its namespace.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.
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
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
/// <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 |
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
namespacekeyword groups related TypeScript code. - The
exportkeyword 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
importandexportare generally preferred for modern applications.