How to Create and Use TypeScript Modules
TypeScript modules offer a structured approach to organizing and managing code. Modules enable encapsulation of code into separate files, which enhances maintainability, reusability, and testability. This guide explains the process of creating and using TypeScript modules.
What are TypeScript Modules?
TypeScript modules are individual files that export and import code elements such as classes, functions, and variables. By employing modules, code can be split into manageable pieces, facilitating better control over interactions between different parts of the code.
Creating a TypeScript Module
To create a TypeScript module, the following steps should be followed:
- Create a TypeScript file: Start by creating a new `.ts` file for the module, such as `mathUtils.ts`.
- Define and export code: Implement functions, classes, or variables within this file and use the
export
keyword to make them available for other modules.
Example of a simple module:
// 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 this example, the `add` and `subtract` functions are defined and exported from the `mathUtils.ts` module.
Importing and Using a TypeScript Module
To utilize the code from a TypeScript module in another file, it must be imported. This involves:
- Create a new TypeScript file: Generate a file where the module's code will be used, such as `app.ts`.
- Import the module: Employ the
import
keyword to bring in functions, classes, or variables from the module.
Example of importing and using the `add` and `subtract` functions:
// app.ts
import { add, subtract } from './mathUtils';
const sum = add(5, 3);
const difference = subtract(5, 3);
console.log(`Sum: ${sum}`);
console.log(`Difference: ${difference}`);
In this example, the `add` and `subtract` functions are imported from the `mathUtils` module and used within the `app.ts` file.
Default and Named Exports
TypeScript modules support both default and named exports. Here is a brief overview:
- Default Exports: A single value can be exported as the default export from a module using
export default
. - Named Exports: Multiple values can be exported from a module using named exports with the
export
keyword.
Example demonstrating both types of exports:
// shapes.ts
export default class Circle {
constructor(public radius: number) {}
area(): number {
return Math.PI * this.radius ** 2;
}
}
export function getCircleInfo(radius: number): string {
const circle = new Circle(radius);
return `A circle with radius ${radius} has an area of ${circle.area()}`;
}
In this example, `Circle` is exported as the default export, while `getCircleInfo` is a named export.
Organizing Modules in a Project
For larger projects with numerous modules, organization becomes crucial. Consider the following tips:
- Directory Structure: Group related modules into directories such as `models/`, `services/`, and `utils/`.
- Index Files: Use `index.ts` files in directories to aggregate and re-export modules, simplifying imports across the project.
Example directory structure:
project/
│
├── src/
│ ├── models/
│ │ ├── index.ts
│ │ └── user.ts
│ └── app.ts
Conclusion
TypeScript modules are a key feature for organizing and managing code. By creating and using modules, code can be kept modular, maintainable, and scalable. Understanding how to export and import code, as well as how to structure a project, enhances the effectiveness of TypeScript development.