What is module augmentation and how do you use it to add a method to an existing library's types?
Short answer
Module augmentation lets you re-open and extend an already-declared module's types from a separate file, by writing `declare module 'existing-module' { ... }` and adding new members — commonly used to add custom properties that a plugin injects onto a library's base types.
Advertisement
AModel answer
Module augmentation lets you re-open and extend an already-declared module's types from a separate file, by writing `declare module 'existing-module' { ... }` and adding new members — commonly used to add custom properties that a plugin injects onto a library's base types.
// express-augment.d.ts
import 'express';
declare module 'express' {
interface Request {
userId?: string; // added by an auth middleware
}
}
// usage.ts
app.get('/', (req) => {
console.log(req.userId); // now recognized
});Real-world example
Adding a custom 'userId' property that an authentication middleware attaches to Express's Request object.
Likely follow-ups
- Why must you 'import' the original module in the augmentation file for this to work correctly?
Related topics