Questions
What is the difference between a `namespace` and a `module` in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are working on a large application and need to find a way to organize your code.
You are not sure whether to use a namespace or a module.
The Challenge
Explain the difference between a namespace and a module in TypeScript. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in scope or the design implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between a `namespace` and a `module`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | namespace | module |
|---|---|---|
| Scope | Creates a new scope for a set of related objects. | A file with a top-level import or export statement. |
export | Objects in a namespace are exported by default. | Objects in a module are not exported by default. |
| Use Cases | For organizing code in a small application or a library. | For organizing code in a large application. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use modules. This is because we are working on a large application, and modules provide a more scalable and maintainable way to organize our code.
In general, you should use modules for all new projects. Namespaces are a legacy feature that should only be used for organizing code in old projects.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
namespace:
namespace MyNamespace {
export const myVar = "hello";
}
console.log(MyNamespace.myVar); // hellomodule:
// my-module.ts
export const myVar = "hello";
// main.ts
import { myVar } from "./my-module";
console.log(myVar); // hello Practice Question
You are working on a large application and you want to organize your code into logical blocks of functionality. Which of the following would you use?