TypeScript Namespaces
🧩 TypeScript Namespaces (Beginner → Advanced)
Namespaces in TypeScript are used to organize code, group related variables/functions/types, and avoid name collisions—especially in large or legacy projects.
⚠️ Note: In modern TypeScript, ES Modules (
import/export) are preferred.
Namespaces are still important for understanding legacy code and interviews.
1️⃣ What Is a Namespace?
A namespace is a container that wraps related code under a single name.
Access it like:
2️⃣ Why Use Namespaces?
✔ Avoid global name conflicts
✔ Logical grouping of code
✔ Useful without module loaders
✔ Common in older TS codebases
3️⃣ Basic Namespace Example ⭐
📌 Members must be marked with export to be accessible outside.
4️⃣ Namespace with Interfaces & Types ⭐
✔ Keeps related types together
5️⃣ Nested Namespaces 🔁
✔ Helps structure large codebases
⚠️ Can get verbose—use carefully
6️⃣ Namespace Across Multiple Files ⭐⭐
File: utils.ts
File: main.ts
📌 Uses triple-slash directives
📌 Old-style dependency management
7️⃣ Namespace vs Module ⭐⭐⭐ (Very Important)
| Feature | Namespace | Module |
|---|---|---|
| Syntax | namespace |
import / export |
| Scope | Global | File-based |
| Modern usage | ❌ Legacy | ✅ Recommended |
| Bundlers | ❌ Not needed | ✅ Works well |
| Tree-shaking | ❌ No | ✅ Yes |
✔ Use modules for new projects
✔ Learn namespaces for legacy & interviews
8️⃣ Namespace Merging 🔥
Multiple declarations with the same namespace name merge automatically.
✔ Powerful but can be confusing
9️⃣ export = and import = (Advanced / Legacy)
⚠️ Mostly used for CommonJS interop
🔟 When NOT to Use Namespaces ❌
-
New applications
-
React / Angular / Node.js apps
-
When using ES modules
-
When bundlers are involved
Use ES Modules instead:
1️⃣1️⃣ Common Mistakes ❌
-
Forgetting
exportinside namespace -
Mixing namespaces with ES modules
-
Over-nesting namespaces
-
Using namespaces in modern projects unnecessarily
📌 Interview Questions (Must Prepare)
-
What is a namespace in TypeScript?
-
Difference between namespace and module?
-
Why are namespaces considered legacy?
-
What is namespace merging?
-
How to use namespaces across files?
-
When should namespaces be avoided?
✅ Summary
✔ Namespaces group related code
✔ Prevent global naming conflicts
✔ Use export to expose members
✔ Support nesting & merging
✔ Mostly legacy, but important to know
✔ Prefer ES modules for modern development
