What are Union Types?
Union types allow a variable to hold multiple possible types using the '|' operator.
Union Example
TypeScriptRead-only
1
What are Intersection Types?
Intersection types combine multiple types into one using the '&' operator, requiring all properties.
Intersection Example
TypeScriptRead-only
1
Union vs Intersection
| Feature | Union (|) | Intersection (&) |
|---|---|---|
| Meaning | Either type | Both types |
| Flexibility | High | Strict |
| Use Case | Multiple options | Combine structures |
Practical Example
TypeScriptRead-only
1
Type Narrowing
TypeScriptRead-only
1
Best Practices
- Use union for flexible inputs
- Use intersection for combining types
- Apply type narrowing for unions
- Keep types readable
Common Mistakes
- Confusing union with intersection
- Not using type narrowing
- Overcomplicating type combinations
- Ignoring type conflicts in intersections
Conclusion
Union and intersection types provide flexibility and structure in TypeScript, enabling powerful type combinations.