Concept Flow - Union vs intersection mental model
Start with Type A
Union: A | B
Intersection: A & B
Use in code to allow flexible or strict types
Union types allow values from either type, intersection types require values to satisfy both types.
type A = { name: string };
type B = { age: number };
let union: A | B = { name: "Alice" };
let intersection: A & B = { name: "Bob", age: 30 };| Step | Variable | Type | Value | Explanation |
|---|---|---|---|---|
| 1 | union | A | B | { name: "Alice" } | Assign object with only 'name' property, valid for union type |
| 2 | union | A | B | { age: 25 } | Assign object with only 'age' property, also valid for union type |
| 3 | union | A | B | { name: "Eve", age: 40 } | Assign object with both properties, valid for union type |
| 4 | intersection | A & B | { name: "Bob", age: 30 } | Assign object with both 'name' and 'age', required for intersection type |
| 5 | intersection | A & B | { name: "Carol" } | Error: missing 'age' property, invalid for intersection type |
| 6 | intersection | A & B | { age: 22 } | Error: missing 'name' property, invalid for intersection type |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | After 6 |
|---|---|---|---|---|---|---|---|
| union | undefined | { name: "Alice" } | { age: 25 } | { name: "Eve", age: 40 } | - | - | - |
| intersection | undefined | - | - | - | { name: "Bob", age: 30 } | Error | Error |
Union (A | B): value can be from type A or type B. Intersection (A & B): value must have all properties from both A and B. Union is flexible, intersection is strict. Use union for alternatives, intersection for combined requirements. Example: let u: A | B; let i: A & B;