What is module augmentation and when would you use it?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Module augmentation lets you add or replace declarations in existing modules — extending third-party types, adding properties to Express's Request, or appending to global interfaces like Window — declared via declare module 'mod' blocks.
Detailed explanation
Libraries evolve slower than your app's needs. Module augmentation merges your declarations into theirs: declare module 'express-serve-static-core' { interface Request { currentUser?: User } } makes req.currentUser type-safe everywhere after auth middleware runs. Same mechanism powers ambient global augmentation (declare global { interface Window { ... } }) for browser APIs you attach at runtime. Rules: augmentations must live in modules (files with import/export), target exported interfaces/classes — not type aliases — and merge structurally like normal declaration merging. Common scenarios: typing middleware-injected request fields, extending React's JSX namespace (JSX.IntrinsicElements custom elements), enriching library instances with plugin metadata, patching generated client types. Cautions: augmentation creates invisible coupling across the codebase — document where augmentations live (a dedicated types.d.ts), keep additions minimal, and prefer contributing upstream when the addition benefits everyone.
Example
// types/express.d.ts
import type { User } from '../auth/user';
declare global {
namespace Express {
interface Request {
currentUser?: User;
}
}
}
// After authMiddleware sets req.currentUser:
app.get('/me', (req, res) => {
res.json(req.currentUser?.name ?? null); // fully typed ✅
});Interview tip
Use the Express Request.currentUser example — nearly every backend dev has felt this pain. Note the 'must be a module file' gotcha to show depth.
Common mistakes
- Attempting to augment type aliases instead of interfaces.
- Putting augmentations in scripts rather than module files, silently failing.