Flexible and Powerful Type Composition
Learn how to combine types in TypeScript using union and intersection types. This module explains union types, intersection types, and real-world use cases with practical examples.
1. Union Types
Union types allow a variable to hold one of multiple possible types. They are defined using the pipe symbol.
Basic Union Type Example
The variable can hold either a number or a string, but not any other type.
Union Types in Functions
Inside the function, type narrowing is often required to safely work with the value.
Type Narrowing Example
Union of Literal Types
Literal unions are commonly used for application states and configuration values.
2. Intersection Types
Intersection types combine multiple types into one. A variable using an intersection type must satisfy all included types.
Basic Intersection Type Example
Using the Intersection Type
Intersection types are useful when an object needs to combine multiple roles or responsibilities.
Intersection with Interfaces
3. Real-World Examples
Handling API Responses
User Authentication Example
This ensures that an authenticated user always has both profile and authentication information.
Form Input Example
Conclusion
Union and intersection types provide flexibility and strong type safety in TypeScript. Union types allow multiple possible values, while intersection types combine multiple structures into one. These concepts are essential for handling complex data models in real-world applications.