Namespaces are a TypeScript-specific way to organize code before ES6 modules became the standard.
They allow you to group related variables, functions, and interfaces logically under a single name.
This prevents naming collisions in the global scope when writing large, monolithic web apps.
While ES modules (import/export) are preferred today, namespaces are still heavily used in older code.
You define a namespace using the namespace keyword followed by its name.
Any variable or function inside it is hidden from the outside world by default.
To make them accessible, you must explicitly use the export keyword inside the block.
This acts as a protective container for related logic tools and utilities.
namespace MathUtility {
export function add(a: number, b: number) {
return a + b;
}
// Hidden function, cannot be accessed outside
function logResult(res: number) { console.log(res); }
}
const sum = MathUtility.add(10, 5); // Works perfectly!
console.log("Sum:", sum);
Namespaces can be infinitely nested within one another to create deep categorization.
You can access nested namespaces by chaining them together with dot notation.
This structure mirrors traditional Object-Oriented languages like Java and C#.
It is particularly useful when defining highly structured API wrapper libraries.
namespace App {
export namespace Database {
export function connect() {
return "Connected to DB!";
}
}
}
console.log(App.Database.connect());
For modern web development and SEO, ES6 modules are far superior to Namespaces.
Bundlers like Webpack and Vite can "Tree Shake" ES modules to remove unused code entirely.
Namespaces do not tree-shake well, resulting in larger bundle sizes and slower page loads.
Only use namespaces when maintaining legacy enterprise applications or writing .d.ts declaration files.
// Namespaces can merge with Classes or Functions to attach static properties!
namespace User {
export const version = "1.0.0";
}
console.log("User Version:", User.version);
Why are ES Modules generally preferred over Namespaces in modern web development?
Understanding namespaces helps you decipher older open-source repositories effectively.
However, always prefer standard import and export for modern projects.
Next, let's explore dynamic objects using Index Signatures!