11
OctModules and Namespaces
Modules and Namespaces in Typescript: An Overview
Modules and Namespaces are strong TypeScript features for organizing and structuring your code. They help in the prevention of naming collisions, the improvement of code readability, and the promotion of code reusability. However, their approaches and applications differ. When diving into a TypeScript tutorial on modules and namespaces, understanding their distinctions becomes crucial for efficient code management and development.Modules in Typescript
- A module is an approach to define a collection of linked variables, functions, classes, interfaces, and so on.
- It runs in the local scope rather than the global scope.
- In other words, variables, functions, classes, and interfaces declared in a module cannot be directly accessed outside of the module.
- We can use the export keyword to construct a module that we can then utilize in other modules by using the import keyword.
Example of Modules in Typescript
math.ts defines a module containing an add function that is exported to other modules. App.ts imports and uses the add function from math.ts, showing modularity and code reuse.// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from "./math";
const result = add(5, 7); // result will be 12
console.log(result);
Namespaces in Typescript
Namespaces organize code within modules or across several files by grouping related declarations (functions, classes, etc.) under a unique identifier.Example of Namespaces in Typescript
The MathUtils namespace contains functions that are related, preventing global name conflicts with other Math functions. The functions add and factorial is exported for external use while remaining organized within the namespace.namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export function factorial(n: number): number {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
console.log(MathUtils.add(5, 7)); // 12
console.log(MathUtils.factorial(5)); // 120
Summary
TypeScript modules and namespaces provide organization and structure. Modules contain code, whereas namespaces contain associated declarations. Both eliminate clashes and improve readability, but modules provide modularity and reusability, whereas namespaces organize within or across modules or files.FAQs
Q1. What are TypeScript namespaces?
Q2. What are modules in TypeScript?
Q3. What are TypeScript modules?
Q4. Why use modules in TypeScript?
Take our Typescript skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.