TypeScript provides namespaces and modules for code organization. Here's when and how to use each.
ES Modules (Recommended)
Re-exporting
Namespaces (Legacy Pattern)
Nested Namespaces
Declaration Merging
Ambient Namespaces
Module Augmentation
Global Augmentation
When to Use What
Module Organization
Best Practices
Modules:
✓ Use ES modules for new code
✓ Use barrel files (index.ts)
✓ Import types with 'import type'
✓ Organize by feature/domain
Namespaces:
✓ Use for global declarations
✓ Use for type augmentation
✓ Keep flat when possible
✓ Document clearly
Avoid:
✗ Mixing modules and namespaces
✗ Deep namespace nesting
✗ Namespaces in modern apps
✗ Circular dependencies
Migration:
✓ Convert namespaces to modules
✓ Use barrel files for grouping
✓ Keep ambient declarations
✓ Update imports gradually
Conclusion
ES Modules are the standard for modern TypeScript. Use them for code organization, tree-shaking, and npm package compatibility. Reserve namespaces for global declarations, type augmentation, and legacy codebases. When migrating, convert namespaces to modules using barrel files for grouping related exports.