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 typenever.
Union type A | B: a value can be either A or B — e.g., string | number allows both.
- Intersection type
A & B: a value must have all properties of both A and B — e.g.,type AdminUser = User & { adminRole: string }creates a type with all User fields plus adminRole. - Use union when a value can be multiple types (flexible parameters), intersection when you need to combine multiple interfaces/types.
- Trap: intersection of two incompatible primitive types (like
string & number) results in the typenever.