0
0
Typescriptprogramming~7 mins

Module augmentation syntax in Typescript

Choose your learning style9 modes available
Introduction

Module augmentation lets you add new features to existing modules without changing their original code. It helps you extend or fix modules safely.

You want to add new functions or types to a library module you use.
You need to fix or improve type definitions from a third-party package.
You want to add extra properties to existing interfaces in a module.
You want to customize behavior of a module without forking or copying it.
Syntax
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.

Examples
This adds an age property to the existing User interface in the my-library module.
Typescript
declare module "my-library" {
  interface User {
    age: number;
  }
}
This adds an optional userId property to Express's Request interface.
Typescript
declare module "express" {
  interface Request {
    userId?: string;
  }
}
This adds a new function newHelper to the some-package module.
Typescript
declare module "some-package" {
  function newHelper(): void;
}
Sample Program

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.

Typescript
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);
OutputSuccess
Important Notes

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.

Summary

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.