DeployU
Interviews / Frontend Engineering / What is the difference between a `namespace` and a `module` in TypeScript?

What is the difference between a `namespace` and a `module` in TypeScript?

conceptual Core Concepts Interactive Quiz Code Examples

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?

Wrong Approach

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.

Right Approach

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

Featurenamespacemodule
ScopeCreates a new scope for a set of related objects.A file with a top-level import or export statement.
exportObjects in a namespace are exported by default.Objects in a module are not exported by default.
Use CasesFor 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); // hello

module:

// 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?