A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/typescript/what-are-the-modules-in-typescript/ below:

What are the Modules in Typescript ?

What are the Modules in Typescript ?

Last Updated : 24 Jan, 2025

Modules in TypeScript allow you to organize code into reusable, manageable, and logical units by encapsulating functionalities into separate files.

math.ts (Module File):

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

main.ts (Importing Module):

JavaScript
import { add } from './math';

const result = add(5, 10);
console.log(result);

Output:

15
Types of modules in TypeScript 1. Internal Module

In earlier versions of TypeScript, internal modules were used to logically group related code, such as variables, functions, classes, and interfaces, into a single unit. This concept has since been replaced by namespaces in TypeScript 1.5 and later versions.

FileName: myNamespace.ts

JavaScript
namespace MyNamespace {
  export function greet(name: string): string {
    return `Hello, ${name}!`;
  }
}

FileName: main.ts

JavaScript
import { MyNamespace } from './myNamespace';

const message = MyNamespace.greet('Alice');
console.log(message);

Output:

Hello, Alice!
2. External Module

External modules, now simply referred to as modules, allow developers to organize code into separate files and reuse components across different parts of an application.

File: mathUtils.ts

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

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

File: app.ts

JavaScript
import { add, subtract } from './mathUtils';

const sum = add(5, 3);
const difference = subtract(5, 3);

console.log(`Sum: ${sum}`);
console.log(`Difference: ${difference}`);

Output:

Sum: 8
Difference: 2
Best Practices for Using Modules in TypeScript

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4