Web Development TypeScript Subjective
Oct 04, 2025

How do union and intersection types work in TypeScript?

Detailed Explanation
Union and intersection types provide powerful ways to combine types in TypeScript. Union Types (|): Allow a value to be one of several types: type StringOrNumber = string | number; type Status = 'loading' | 'success' | 'error'; function printId(id: string | number) { if (typeof id === 'string') { console.log(id.toUpperCase()); } else { console.log(id.toFixed(2)); } } Intersection Types (&): Combine multiple types into one, requiring all properties: interface Person { name: string; age: number; } interface Employee { employeeId: number; department: string; } type PersonEmployee = Person & Employee; const worker: PersonEmployee = { name: 'John', age: 30, employeeId: 123, department: 'IT' }; Key Differences: • Union: Value can be ANY of the types • Intersection: Value must have ALL properties from combined types • Union narrows with type guards • Intersection creates new composite type.
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback