Difference Between Namespace and Module in Typescript

1. Introduction

In TypeScript, understanding the difference between namespaces and modules is key to organizing code effectively. A namespace is a TypeScript-specific way to group related code. It can be used to organize code into logical groups and avoid name collisions. A module, on the other hand, is the standard TypeScript and ES6 way to divide code into separate files, each of which can export variables, functions, or types.

2. Key Points

1. Scope: Namespaces are global in scope, while modules are file-based.

2. Declaration: Namespaces are declared with the namespace keyword, modules use export and import.

3. File Structure: Namespaces can be in one or multiple files, while modules correspond to files.

4. Use in Modern Applications: Modules are preferred in modern TypeScript applications due to better tooling and compatibility with the ES6 standard.

3. Differences

Characteristic Namespace Module
Scope Global File-based
Declaration With namespace keyword With export and import
File Structure Can be in one or multiple files One module per file
Use in Modern Applications Less common Preferred for compatibility with ES6

4. Example

// Example of Namespace
namespace MyNamespace {
    export class MyClass {
        myMethod() {}
    }
}

// Example of Module
// In file myModule.ts
export class MyModuleClass {
    moduleMethod() {}
}

// In another file
import { MyModuleClass } from './myModule';

Output:

No direct output as these are structural code examples.

Explanation:

1. MyNamespace is a namespace that groups MyClass under a common name. It can be accessed globally if properly referenced.

2. MyModuleClass is part of a module, which is imported from myModule.ts. Each module is distinct and manages its own dependencies through imports and exports.

5. When to use?

- Use namespaces in TypeScript if you are working on a legacy codebase or for simple applications where you want to group related functionality.

- Use modules for modern TypeScript development, especially when building large-scale applications or when you need to ensure compatibility with JavaScript ES6.

Comments