TypeScript / TypeScript Modules and Namespaces
Creating and Using Modules in TypeScript
This tutorial will guide you on how to create and use modules in TypeScript. Modules allow you to organize your code into reusable pieces.
Section overview
5 resourcesCovers the module system in TypeScript, including imports, exports, and namespaces.
Introduction
The goal of this tutorial is to guide you through the process of creating and using modules in TypeScript. Modules are a fundamental aspect of scalable design in TypeScript as they help to encapsulate related code into single, independent parts of the program.
In this tutorial, you will learn:
- What are modules in TypeScript
- How to create modules in TypeScript
- How to import and use modules in TypeScript
Prerequisites:
- Basic understanding of TypeScript
- A setup environment to run TypeScript code
Step-by-Step Guide
What are modules?
Modules in TypeScript are a way of organizing code into reusable pieces. You can think of them as mini-programs that can be included in your main application to perform specific tasks.
Creating a Module
To create a module in TypeScript, you simply define a TypeScript file and export the functionalities, which could be variables, functions, classes, or interfaces, that you want to expose to other parts of your application.
Here's a simple example of 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;
}
In the example above, we created a module math.ts that exports two functions, add and subtract.
Using a Module
To use a module in another TypeScript file, you'll need to import it using the import statement.
Here's how you can import and use the math.ts module:
// app.ts
import * as math from './math';
console.log(math.add(1, 2)); // Outputs: 3
console.log(math.subtract(3, 2)); // Outputs: 1
In the example above, we imported the math module into our app.ts file. We then used the add and subtract functions from the math module.
Code Examples
Let's create a more practical module and use it in our application.
- We'll create a module that handles all operations related to a
Todolist.
// todo.ts
export interface Todo {
id: number;
task: string;
done: boolean;
}
let todoList: Todo[] = [];
export function addTodo(task: string) {
const todo: Todo = {
id: todoList.length + 1,
task,
done: false,
};
todoList.push(todo);
}
export function getTodos(): Todo[] {
return todoList;
}
In the code above, we defined a Todo interface and two functions, addTodo and getTodos.
- Now, let's use this module in our application:
// app.ts
import * as todoModule from './todo';
todoModule.addTodo('Learn TypeScript');
todoModule.addTodo('Learn Modules');
console.log(todoModule.getTodos());
// Outputs: [ { id: 1, task: 'Learn TypeScript', done: false }, { id: 2, task: 'Learn Modules', done: false } ]
In the code above, we added two tasks to our todo list and then logged the entire list to the console.
Summary
In this tutorial, you've learned what modules are in TypeScript, how to create them, and how to import and use them in your applications. Modules are a great way to organize your code and make it more manageable and scalable.
For further learning, you could explore how to create and use namespaces, how to use default exports, and how to use the export = and import = require() syntax in TypeScript.
Practice Exercises
-
Create a module that exports a function which returns the length of a string. Use this module in another TypeScript file.
-
Create a module that exports a class
Personwith propertiesnameandageand a methodsayHellothat outputs "Hello, my name is {name} and I am {age} years old". Import this class in another TypeScript file, create an instance ofPerson, and call thesayHellomethod. -
Create a module that exports an interface
Studentwith propertiesname,age, andgrades(an array of numbers), and a functioncalculateAverageGradethat takes an array ofStudentobjects and returns the average grade. Use this module in another TypeScript file.
Remember to try these exercises on your own before checking the solutions, and feel free to modify and experiment with the code to better understand how modules work in TypeScript.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article