![]() |
VOOZH | about |
Module Augmentation is a feature of TypeScript that extends or modifies existing modules without making direct changes in the original code. This is very useful when we are handling third-party libraries that cannot be modified. We can use module augmentation to add new functionality to an existing module, making it more versatile.
Module Augmentation allows us to add new functionality to existing modules. We can extend libraries or add new functionalities modules that are written by any other developer without changing the actual code of the library. This is commonly used with third-party libraries. Suppose, we are using a library and need to add more functions or features that were not initially present or provided in it, we can use module augmentation to do so in our own project without changing the library itself.
In TypeScript, modules which are also known as namespaces can be augmented by reopening the module and adding new types, functions, or variables. This concept is the same as extending classes or adding methods to prototypes in JavaScript.
npm init -ynpm install typescript --save-devnpx tsc --initdeclare module 'math-lib' {
export function subtract(x: number, y: number): number;
}
import { subtract } from './math-lib';
const difference = subtract(10, 4);
console.log('Difference:', difference);
export function subtract(x: number, y: number): number {
return x - y;
}
Example: In this example we will use the Module Augmentation
Compile TypeScript: In the terminal, we type the following command to compile our TypeScript files into JavaScript:
npx tscThis command will convert our .ts files into .js files, which you can run using Node.js.
node app.jsOutput:
Difference: 6Module augmentation is a useful feature in TypeScript that is used to extend existing modules in a very clean way. It is useful when we deal with third-party libraries or legacy code. We have seen a simple example above which shows how o augment a simple module and use it within your TypeScript project.