In TypeScript, a module is a way to encapsulate code and manage dependencies between different parts of an application. Modules help in organizing code into reusable pieces, making it easier to maintain and scale applications. They can export variables, functions, classes, or interfaces, which can then be imported into other modules. This modular approach promotes better code organization and separation of concerns.
Modules in TypeScript are based on the ES6 module system, which allows developers to use the `import` and `export` keywords to share code between files. This is particularly useful in larger applications where keeping code organized is essential for maintainability.
Internal modules, now referred to as namespaces, were used in earlier versions of TypeScript to group related code together. However, they are not recommended for new projects. Instead, using ES6 modules is the preferred approach.
External modules are the standard way to create modules in TypeScript. They are defined in separate files and can be imported into other files. Each file is treated as a module, and the code within it is scoped to that module.
To create a module in TypeScript, you can define a file with a `.ts` extension and use the `export` keyword to expose parts of the module. Here’s a simple example:
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
In the example above, we have a module named `mathUtils` that exports two functions: `add` and `subtract`.
To use the exported functions from the `mathUtils` module in another file, you would import them as follows:
// main.ts
import { add, subtract } from './mathUtils';
const sum = add(5, 3);
const difference = subtract(5, 3);
console.log(`Sum: ${sum}, Difference: ${difference}`);
In summary, modules in TypeScript are a powerful feature that enhances code organization and reusability. By following best practices and avoiding common pitfalls, developers can create maintainable and scalable applications.