TypeScript modules are a powerful feature for organizing and structuring code in larger applications. They provide a way to encapsulate related functionality and control visibility of variables, functions, and classes.
Modules in TypeScript are similar to JavaScript modules. They allow you to split your code into separate files, each containing a portion of your application's functionality. This separation promotes code reusability and maintainability.
To create a module in TypeScript, simply write your code in a separate .ts file. Any declarations in this file are scoped to the module and not visible globally unless explicitly exported.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;
Use the export
keyword to make declarations available outside the module. You can export variables, functions, classes, and interfaces.
For more details on exporting, check out the guide on Export and Import in TypeScript.
To use functionality from another module, use the import
statement. You can import specific items or the entire module.
// app.ts
import { add, PI } from './math';
console.log(add(2, 3)); // Outputs: 5
console.log(PI); // Outputs: 3.14159
TypeScript uses various strategies to resolve module imports:
The resolution strategy can be configured in your tsconfig.json file.
TypeScript allows you to extend existing modules with new functionality. This is particularly useful when working with third-party libraries.
// augmentation.ts
import { MyModule } from 'some-library';
declare module 'some-library' {
interface MyModule {
newFunction(): void;
}
}
MyModule.prototype.newFunction = function() {
console.log('New functionality added!');
};
Understanding modules is crucial for building scalable TypeScript applications. They provide a foundation for organizing code and managing dependencies effectively.
For more advanced module concepts, explore Dynamic Imports and Ambient Modules in TypeScript.