Cơ BảnTypeScript iconTypeScript

Union types và intersection types là gì?

Union type A | B: value có thể là A hoặc B — ví dụ string | number cho phép cả hai.

  • Intersection type A & B: value phải có tất cả properties của A lẫn B — ví dụ type AdminUser = User & { adminRole: string } tạo type có đủ fields của User cộng thêm adminRole.
  • Union dùng khi một giá trị có thể là nhiều loại (parameter linh hoạt), intersection dùng khi cần combine nhiều interface/type lại.
  • Bẫy: intersection của 2 primitive types không tương thích (như string & number) cho ra type never.

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

Mở danh sách TypeScript