Typescript - Union vs Intersection types

· 207 words · 1 minute read

Union Types 🔗

Multiple types can be defined on a value by using the | symbol. When a value is expected to have one of many known types, then using union type is the most suitable option (rather than any or unknown).

type value = number | boolean;

Here value can be either number or boolean.

We can also combine custom type using the union operator.

interface house {
  hasDoor: boolean;
  address: string;
}

interface building {
  hasLift: boolean;
  address: string;
}

type houseOrBuilding = house | building

const hb: houseOrBuilding

In above case hb can only access members that are common to all types in the union.


Intersection Types 🔗

Intersection types on the other hand are useful when we want to combine two or more types to create a custom type. The difference from Union Type is that the types create using intersection will have all members of the combined types. We use & symbol to combine types.

Lets reuse the above example,

interface house {
  hasDoor: boolean;
  address: string;
}

interface building {
  hasLift: boolean;
  address: string;
}

type houseAndBuilding = house & building

const hb: houseAndBuilding

The value hb needs to have all 3 properties (hasDoor, hasLift and address) to be a valid houseAndBuilding type.