Module augmentation cho phép thêm types vào module đã có.
- Dùng để extend third-party types mà không fork.
- Cần import module đó (ambient augmentation vs global augmentation).
- Rất hữu ích cho middleware patterns.
typescript
// Thêm user vào Express Request (pattern phổ biến với auth middleware)
declare module 'express' {
interface Request {
user?: { id: string; role: string };
}
}
// Trong route:
app.get('/me', (req, res) => {
res.json(req.user); // TS biết type của user
});Module augmentation allows adding types to an existing module.
- Used to extend third-party types without forking.
- Requires importing the module (ambient augmentation vs global augmentation).
- Very useful for middleware patterns.
typescript
// Add user to Express Request (common auth middleware pattern)
declare module 'express' {
interface Request {
user?: { id: string; role: string };
}
}
// In route handler:
app.get('/me', (req, res) => {
res.json(req.user); // TS knows the type of user
});