Internal modules in TypeScript are primarily designed to organize and encapsulate code functionality, and they are now referred to as "namespaces". Internal modules were commonly used in early versions of TypeScript, but since the ES2015 module standard has been widely adopted, TypeScript recommends using ES modules to manage code and dependencies.
Internal modules (namespaces) are primarily defined using the namespace keyword to address global scope pollution. They allow functions, interfaces, classes, and other elements to be encapsulated within a closed scope, with only necessary components exported.
Example:
Suppose we are developing a math library that includes functions for matrix operations; we can use internal modules to organize these functions:
typescriptnamespace MathLib { export class Matrix { // Constructor constructor(public elements: number[][]) {} // Matrix addition method static add(m1: Matrix, m2: Matrix): Matrix { let resultElements = m1.elements.map((row, i) => row.map((val, j) => val + m2.elements[i][j]) ); return new Matrix(resultElements); } } } // Usage: let matrix1 = new MathLib.Matrix([[1, 2], [3, 4]]); let matrix2 = new MathLib.Matrix([[5, 6], [7, 8]]); let matrixSum = MathLib.Matrix.add(matrix1, matrix2); console.log(matrixSum.elements);
In this example, the MathLib namespace encapsulates all matrix-related operations. By exporting the Matrix class using the export keyword, it becomes accessible outside the namespace. This approach effectively avoids global scope pollution and enhances code structure clarity and manageability.
In summary, although TypeScript now recommends using ES modules (with import and export), internal modules (namespaces) remain a valuable tool for organizing and encapsulating code in specific scenarios.