0
0
Typescriptprogramming~5 mins

Why module augmentation is needed in Typescript

Choose your learning style9 modes available
Introduction

Module augmentation lets you add new features or fix things in existing code without changing the original files. It helps keep your code organized and safe.

You want to add new functions or types to a library you use but can't edit its code.
You need to fix or improve type definitions from a third-party package.
You want to add extra properties to existing objects or modules in your project.
You want to customize behavior of a module without copying or rewriting it.
Syntax
Typescript
declare module 'module-name' {
  // add new types, interfaces, or values here
}
Use declare module with the exact module name you want to extend.
Put your additions inside the curly braces to safely add to the module.
Examples
This adds a new optional userId property to the Request interface from the Express library.
Typescript
declare module 'express' {
  interface Request {
    userId?: string;
  }
}
This adds a new function newFeature to your own module myModule.
Typescript
declare module './myModule' {
  export function newFeature(): void;
}
Sample Program

This example shows how to add a new property userId to Express's Request object using module augmentation. Then it uses that property in middleware and a route.

Typescript
import express from 'express';

// Module augmentation to add userId to Request

declare module 'express' {
  interface Request {
    userId?: string;
  }
}

const app = express();

app.use((req, res, next) => {
  req.userId = 'abc123';
  next();
});

app.get('/', (req, res) => {
  res.send(`User ID is ${req.userId}`);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
OutputSuccess
Important Notes

Module augmentation only changes types or declarations, it does not change runtime code by itself.

Always use the exact module name as in the original import to avoid errors.

Summary

Module augmentation helps you safely add or fix types in existing modules.

It is useful when you can't or don't want to change original code.

Use declare module 'name' with additions inside curly braces.