How to use union and intersection types
· Category: TypeScript
Short answer
Union types (A | B) allow a value to be one of several types. Intersection types (A & B) require a value to satisfy all combined types.
Steps
- Declare a union:
type ID = string | number; - Narrow a union using
typeof,in, or custom type guards before accessing type-specific properties. - Declare an intersection:
type Employee = Person & HasId; - Use intersections to mix multiple object shapes into one.
- Combine unions and intersections for advanced modeling.
Tips
- Discriminated unions with a shared literal property make narrowing straightforward and type-safe.
- Intersections can produce
neverif primitive types conflict, such asstring & number.
Common issues
- Accessing a property that exists on only one member of a union causes a compile error without narrowing.
- Overusing intersections can create bloated types that are hard to read and maintain.