Nâng CaoTypeScript iconTypeScript

Module augmentation là gì?

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
});

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript