Back to Course

Learn TypeScript

0% Complete
0/0 Steps
Lesson 22 of 25
In Progress

Modules in Typescript

Modules are an essential part of any large-scale application in Typescript. They allow you to organize your code into reusable units that can be imported and used in other parts of your application. In this article, we will cover the basics of modules in Typescript, including how to declare and import them, as well as how to use them to organize and structure your code.

What are Modules in Typescript?

Modules in Typescript are used to organize and structure your code into reusable units. They can contain functions, classes, interfaces, and even other modules, and can be imported and used in other parts of your application. Modules are a powerful tool for separating concerns and ensuring that your code is easy to understand and maintain.

Declaring Modules

There are two ways to declare a module in Typescript: using the export keyword and using the namespace keyword.

To declare a module using the export keyword, you simply need to add the export keyword in front of any functions, classes, or interfaces that you want to make available for use in other parts of your application. For example:

export function sayHello(name: string) {
  console.log(`Hello, ${name}!`);
}

export class User {
  constructor(public name: string, public age: number) {}
}

To declare a module using the namespace keyword, you can use the following syntax:

namespace MyModule {
  export function sayHello(name: string) {
    console.log(`Hello, ${name}!`);
  }

  export class User {
    constructor(public name: string, public age: number) {}
  }
}

Importing Modules

To import a module in Typescript, you can use the import keyword and specify the name of the module and the functions, classes, or interfaces that you want to import. For example:

import { sayHello } from "./myModule";
import { User } from "./myModule";

sayHello("John"); // Outputs "Hello, John!"
const user = new User("John", 30);

You can also use the import * as syntax to import all the exports of a module into a single object:

import * as myModule from "./myModule";

myModule.sayHello("John"); // Outputs "Hello, John!"
const user = new myModule.User("John", 30);

Exporting and Importing Types

In addition to exporting and importing functions and classes, you can also export and import types in Typescript. To do this, you can use the export type syntax:

export type User = {
  name: string;
  age: number;
};

To import a type, you can use the import type syntax:

import type { User } from "./myModule";

const user: User = {
  name: "John",
  age: 30,
};

Using Modules to Organize Code

One of the main benefits of using modules in Typescript is that they allow you to organize and structure your code in a logical and easy-to-understand way. For example, you can use modules to separate different parts of your application into different files and folders, making it easier to find and maintain your code.

You can also use modules to organize your code by feature or functionality. For example, you might have a separate module for handling user authentication, a separate module for managing data storage, and a separate module for handling UI components. This makes it easier to understand and maintain your code, as well as to reuse code between different parts of your application.

Conclusion

Modules are an essential part of any large-scale Typescript application, and are a powerful tool for organizing and structuring your code. They allow you to declare and import functions, classes, interfaces, and even other modules, and are a great way to ensure that your code is easy to understand and maintain.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Create a module called MathUtils that contains a function called add that takes in two numbers and returns their sum. Import and use the add function in another file.

MathUtils.ts

export function add(a: number, b: number) {
  return a + b;
}

main.ts

import { add } from "./MathUtils";

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

Create a module called User that contains a class with the same name. The class should have three properties: name, age, and email. Add an introduce method to the class that outputs the user’s name and email. Import and use the User class in another file.

User.ts

export class User {
  constructor(public name: string, public age: number, public email: string) {}

  introduce() {
    console.log(`Hi, my name is ${this.name} and my email is ${this.email}.`);
  }
}

main.ts

import { User } from "./User";

const user = new User("John", 30, "john@example.com");
user.introduce(); // Outputs "Hi, my name is John and my email is john@example.com."

Create a module called Product that contains an interface with the same name. The interface should have two properties: name and price. Create a function called calculateTotalPrice that takes in an array of Product interfaces and returns the total price of all the products. Import and use the Product interface and the calculateTotalPrice function in another file.

Product.ts

export interface Product {
  name: string;
  price: number;
}

export function calculateTotalPrice(products: Product[]) {
  return products.reduce((total, product) => total + product.price, 0);
}

main.ts

import { Product, calculateTotalPrice } from "./Product";

const products: Product[] = [
  { name: "Product 1", price: 10 },
  { name: "Product 2", price: 20 },
  { name: "Product 3", price: 30 },
];

console.log(calculateTotalPrice(products)); // Outputs 60

Create a module called Utils that exports multiple functions: add, subtract, multiply, and divide. Each function should take in two numbers and return the result of the corresponding mathematical operation. Import and use these functions in another file.

Utils.ts

export function add(a: number, b: number) {
  return a + b;
}

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

export function multiply(a: number, b: number) {
  return a * b;
}

export function divide(a: number, b: number) {
  return a / b;
}

main.ts

import { add, subtract, multiply, divide } from "./Utils";

console.log(add(2, 3)); // Outputs 5
console.log(subtract(2, 3)); // Outputs -1
console.log(multiply(2, 3)); // Outputs 6
console.log(divide(2, 3)); // Outputs 0.6666666666666666

Create a module called Color that exports an enum with the same name. The enum should contain the colors red, green, and blue. Create a function called getColorName that takes in a color value and returns the corresponding color name. Import and use the Color enum and the getColorName function in another file.

Color.ts

export enum Color {
  Red,
  Green,
  Blue,
}

export function getColorName(color: Color) {
  switch (color) {
    case Color.Red:
      return "Red";
    case Color.Green:
      return "Green";
    case Color.Blue:
      return "Blue";
  }
}

main.ts

import { Color, getColorName } from "./Color";

console.log(getColorName(Color.Red)); // Outputs "Red"
console.log(getColorName(Color.Green)); // Outputs "Green"
console.log(getColorName(Color.Blue)); // Outputs "Blue"