Back to Blog
TypeScriptNamespacesModulesOrganization

TypeScript Namespaces vs Modules

Understand TypeScript namespaces and modules for organizing and structuring code.

B
Bootspring Team
Engineering
December 10, 2018
6 min read

TypeScript provides namespaces and modules for code organization. Here's when and how to use each.

Loading code block...

Re-exporting#

Loading code block...

Namespaces (Legacy Pattern)#

Loading code block...

Nested Namespaces#

Loading code block...

Declaration Merging#

Loading code block...

Ambient Namespaces#

Loading code block...

Module Augmentation#

Loading code block...

Global Augmentation#

Loading code block...

When to Use What#

Loading code block...

Module Organization#

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles