Intermediate 16 min readModule: Module 4: Union, Intersection & Literal Types
Union (|) & Intersection (&) Types
Model complex real-world data structures with union types and merge contracts with intersections.
What You Will Learn in This Lesson
- Union types (|) for values that can be one of several types
- Intersection types (&) to combine multiple object shapes
- Template literal types (e.g. `on${Capitalize<string>}`)
Introduction & Core Concept
Union and intersection types allow you to compose existing types into sophisticated, expressive domain models.
WHY DOES THIS MATTER IN THE REAL WORLD?
Unions model states like 'pending' | 'success' | 'error' without messy numeric flags.
Union State & Intersection Merge
typescripttypescript
1234567type Status = "idle" | "loading" | "success" | "error";type Timestamps = { createdAt: Date; updatedAt: Date };type Article = { title: string; body: string };type PersistedArticle = Article & Timestamps;console.log("Composed persistent entity types cleanly.");
Line-by-Line Technical Breakdown
1Unions require type narrowing before accessing member-specific properties.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[TYPESCRIPT]
TYPESCRIPT SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Use literal unions for finite state machines.
Lesson Summary & Core Takeaways
- Unions and intersections provide flexible type composition.