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

  1. Declare a union: type ID = string | number;
  2. Narrow a union using typeof, in, or custom type guards before accessing type-specific properties.
  3. Declare an intersection: type Employee = Person & HasId;
  4. Use intersections to mix multiple object shapes into one.
  5. Combine unions and intersections for advanced modeling.

Tips

  • Discriminated unions with a shared literal property make narrowing straightforward and type-safe.
  • Intersections can produce never if primitive types conflict, such as string & 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.