Q7: What is the difference between Union Types (`|`) and Intersection Types (`&`)?
- Union Type (
A | B): Represents a value that can be either typeAor typeB. You can only access properties common to both types unless narrowed. - Intersection Type (
A & B): Combines multiple type structures into one. The resulting value must satisfy both type contracts simultaneously.
Union vs Intersection
type Admin = { name: string; permissions: string[] };
type User = { name: string; email: string };
// Union: Must be Admin OR User
type Account = Admin | User;
// Intersection: Must have ALL properties from Admin AND User
type SuperAdmin = Admin & User;💡 Intersection types merge structural constraints, requiring all combined properties.
Key Takeaways
- Unions allow one of several types; Intersections merge multiple types into one.