Open In App

Difference Between Internal & External Modules in TypeScript

In TypeScript, modules are a way to organize code and encapsulate functionality. There are two types of modules: internal modules (also known as namespaces) and external modules (also known as modules).

Internal Modules (Namespaces):

Internal modules, known as namespaces, provide a way to organize code within a single global scope. They help in avoiding naming conflicts by encapsulating code within a named container.



Syntax:

namespace MyNamespace {
// code within the namespace
}

Example: Here, a namespace named MathOperations is created to group mathematical functions like addition and subtraction. The functions are then accessed within the namespace, showcasing the encapsulation provided by internal modules.




namespace MathOperations {
    export function add(x: number, y: number): number {
        return x + y;
    }
 
    export function subtract(x: number, y: number): number {
        return x - y;
    }
}
 
// Usage
let resultAdd = MathOperations.add(5, 3);
let resultSubtract = MathOperations.subtract(8, 2);
 
console.log(resultAdd);      // Output: 8
console.log(resultSubtract); // Output: 6

Output:



8
6

External Modules

External modules allow you to organize code into separate files. Each file is treated as a separate module, and you can explicitly export and import functionalities between these modules. It is also known as the ES6 module.

Syntax: File 1 (moduleA.ts):

// moduleA.ts
export const variableA = 10;
export function functionA(): void {
// code
}

File 2 (moduleB.ts):

// moduleB.ts
import { variableA, functionA } from './moduleA';
// code using variableA and functionA

Example: Here, moduleA.ts defines a namespace MathOperations, and moduleB.ts imports and uses the functionalities from moduleA.




// moduleA.ts
export namespace MathOperations {
    export function add(x: number, y: number): number {
        return x + y;
    }
 
    export function subtract(x: number, y: number): number {
        return x - y;
    }
}




// moduleB.ts
import { MathOperations } from './moduleA';
 
// Usage
let resultAdd = MathOperations.add(5, 3);
let resultSubtract = MathOperations.subtract(8, 2);
 
console.log(resultAdd);      // Output: 8
console.log(resultSubtract); // Output: 6

Output:

8
6

Article Tags :