Module augmentation lets you add new features to existing modules without changing their original code. It helps you extend or fix modules safely.
Module augmentation syntax in Typescript
declare module "module-name" { // add new types, interfaces, or values here interface ExistingInterface { newProperty: string; } function newFunction(): void; }
Use declare module "module-name" to tell TypeScript you want to add to that module.
Only add new things or extend existing ones; do not redefine completely.
age property to the existing User interface in the my-library module.declare module "my-library" { interface User { age: number; } }
userId property to Express's Request interface.declare module "express" { interface Request { userId?: string; } }
newHelper to the some-package module.declare module "some-package" { function newHelper(): void; }
This program adds a new optional property userRole to Express's Request interface using module augmentation. Then it creates a request object, sets the user role, and prints it.
import { Request } from "express"; declare module "express" { interface Request { userRole?: string; } } function printUserRole(req: Request) { if (req.userRole) { console.log(`User role is: ${req.userRole}`); } else { console.log("User role is not set."); } } const req = {} as Request; req.userRole = "admin"; printUserRole(req);
Module augmentation only works if the module is imported or referenced in your code.
Be careful not to overwrite existing types; always extend them.
Use module augmentation to keep your code compatible with library updates.
Module augmentation lets you add or extend types in existing modules.
Use declare module "module-name" to start augmentation.
It helps customize or fix third-party modules without changing their source.