Modules and Namespaces in TypeScript
Modules and Namespaces in TypeScript
Let’s break down Modules and Namespaces in TypeScript — both are mechanisms for organizing and reusing code, but they serve slightly different purposes and are used differently.
🔹 Modules in TypeScript
✅ What is a Module?
A module is a file that contains code (classes, interfaces, functions, variables, etc.) and exports them so they can be reused in other files by importing.
🔧 How to Create and Use a Module
math.ts
(a module)
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14;
main.ts
(importing the module)
import { add, PI } from './math';
console.log(add(5, 10)); // 15
console.log(PI); // 3.14
Modules follow ES6 module syntax and are commonly used in Angular and modern TypeScript projects.
🔹 Namespaces in TypeScript
✅ What is a Namespace?
A namespace is a way to group related code within a single file or across multiple files to avoid global scope pollution.
Think of it as a container (like a class) for organizing code logically.
🔧 How to Use a Namespace
namespace MathUtil {
export function multiply(a: number, b: number): number {
return a * b;
}
export function square(x: number): number {
return x * x;
}
}
console.log(MathUtil.multiply(2, 5)); // 10
console.log(MathUtil.square(4)); // 16
⚠️ Important Note
Namespaces were popular before modules became standard. In modern TypeScript (and Angular), modules are preferred over namespaces.
🔄 Comparison Table
Feature | Modules | Namespaces |
---|---|---|
Scope | File-based | Global or file-based |
Syntax | import / export |
namespace + export |
Use in Angular | ✅ Yes | ❌ Rarely used |
Compilation | Uses ES Modules / CommonJS | Uses global scope unless modularized |
🧠Summary
- Use modules in Angular and modern TypeScript development.
- Avoid namespaces unless working in older or non-module projects.
- Modules promote better structure, testability, and dependency management.
Comments
Post a Comment