TypeScript Modules and Namespaces in 2025: ES Modules, Import/Export, Default vs Named, and Best Practices

1. What are modules and namespaces in TypeScript?

Q: What is the difference between modules and namespaces?

Modules (especially ES Modules) are the modern, file-based way to organize and share code using import and export. They align with JavaScript standards and are recommended for all new projects.

Namespaces are a legacy TypeScript feature (formerly "internal modules") for grouping code logically within the global scope using the namespace keyword.

Key Difference: Modules are preferred in 2025 – namespaces are mainly for legacy code or simple scripts.

2. What are ES Modules in TypeScript, and how do import and export work?

Q: How do ES Modules work in TypeScript?

ES Modules use standard import/export syntax and are configured with "module": "ESNext" or "NodeNext" in tsconfig.json.

Example code remains excellent – see original for mathUtils.ts and main.ts.

3. What are default exports vs. named exports in TypeScript?

Q: Default vs named exports – which to use?

Use named exports for multiple related items; default for a single primary export (e.g., a main class).

Excellent example with calculator.ts – no changes needed.

4. What are namespaces in TypeScript, and when to use them?

Q: Are namespaces still relevant in 2025?

Namespaces are mostly legacy. Use them only for small scripts or migrating old code. Modern projects should use ES modules.

Example with utils.ts remains valid for illustration.

5. Comprehensive example combining modules and namespaces

Great real-world demo of interoperability (exporting a namespace from a module). Content unchanged – highly useful for migration scenarios.

6. What are common mistakes in TypeScript modules and namespaces?

Q: What pitfalls to avoid?

7. What are best practices for TypeScript modules and namespaces in 2025?

Q: Modern best practices?