You are currently viewing TypeScript Modules Tutorial: Learn How to Organize Your Code

TypeScript Modules Tutorial: Learn How to Organize Your Code

Introduction to TypeScript Modules

TypeScript, a superset of JavaScript, offers a powerful module system that allows you to organize your code into reusable and manageable pieces. In this tutorial, we’ll delve into TypeScript modules, exploring how to create, import, and export modules effectively.

1. What are TypeScript Modules?

TypeScript modules are a way to organize code into separate files. Each file represents a module, which can contain variables, functions, classes, or interfaces.

2. Creating a Module

Let’s start by creating a simple module. Create a new file named math.ts:

// math.ts
export function add(a: number, b: number): number {
    return a + b;
}

In this module, we have a function add that adds two numbers and exports it using the export keyword.

3. Importing Modules

Now, let’s import the add function from the math module into another file:

// main.ts
import { add } from "./math";

console.log(add(2, 3)); // Output: 5

Here, we import the add function from the math module using the import statement.

4. Exporting Multiple Entities

You can export multiple entities from a module:

// math.ts
export function add(a: number, b: number): number {
    return a + b;
}

export function subtract(a: number, b: number): number {
    return a - b;
}

Now, you can import both add and subtract functions in another file:

// main.ts
import { add, subtract } from "./math";

console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2

5. Default Exports

You can also have a default export in a module:

// math.ts
export default function add(a: number, b: number): number {
    return a + b;
}

And import it like this:

// main.ts
import add from "./math";

console.log(add(2, 3)); // Output: 5

6. Re-Exports

You can re-export entities from one module to another:

// math.ts
export function add(a: number, b: number): number {
    return a + b;
}
// utils.ts
export { add as addition } from "./math";
// main.ts
import { addition } from "./utils";

console.log(addition(2, 3)); // Output: 5

Conclusion

TypeScript modules are an essential part of organizing and managing your codebase effectively. By leveraging modules, you can create reusable and maintainable code, leading to better scalability and readability in your projects.

This tutorial covered the basics of TypeScript modules, including creating modules, importing and exporting entities, default exports, and re-exports. Start incorporating modules into your TypeScript projects to unlock their full potential.

Leave a Reply