HomeAbout

Union and Intersection

Union (|) Type

Variable can hold a value of either types defined

  • any one of several types
const varName = string | number;

varName variable can be either string type or number type

varName = "3"; // allowed varName = 3; // allowed

Intersection Types (&)

Creates a single new type by combining multiple existing types

type typeAB = typeA & typeB;
  • The typeAB will have all properties from both typeA and typeB.

When to use Union vs Intersection

If a union is an OR, then an intersection is an AND

Property Collision

When you have multiple type intersections like this example:

type MultipleIntersection = TypeA & TypeB & TypeC;

And intersection has a property that is defined multiple times of different types, you will get an error

interface TypeA { id: number; name: string; } interface TypeB { id: string; age: number; } // conflicting `id` property, will error type ErroringIntersection = TypeA & TypeB

Order of typing

Order of type intersection does not matter

type typeAB = typeA & typeB; type typeBA = typeB & typeA;

Type typeAB and typeBA have the same properties.

AboutContact