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.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers 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.

  1. We'll create a module that handles all operations related to a Todo list.
// 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.

  1. 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

  1. Create a module that exports a function which returns the length of a string. Use this module in another TypeScript file.

  2. Create a module that exports a class Person with properties name and age and a method sayHello that outputs "Hello, my name is {name} and I am {age} years old". Import this class in another TypeScript file, create an instance of Person, and call the sayHello method.

  3. Create a module that exports an interface Student with properties name, age, and grades (an array of numbers), and a function calculateAverageGrade that takes an array of Student objects 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help