Published on

Easily Combining Types in TypeScript Using the Ampersand Character

Authors

TypeScript makes it super easy to define types where you simply define the type inline or/and define an interface for it (I find it much simpler and cleaner than defining beans in some c-like languages).

Today I came across a type defined as:

type DirectionOrdinal = Direction & Ordinal

After a quick search I found that this feature is referred to as intersection. Essentially what it lets you do is define a type that merges the properties define in the other types used in the intersection.

To clarify I will include the full code before the intersection mentioned above:

enum Direction {
  Left = 'Leftwards',
  Right = 'Rightwards',
  Up = 'Upwards',
  Down = 'Downwards',
}

enum Ordinal {
  North = 'North',
  South = 'South',
  East = 'East',
  West = 'West',
}

type DirectionOrdinal = Direction & Ordinal

DirectionOrdinal in this case is an enum that can be any of Direction or Ordinal. Intersection can also be used on interface definitions and type definitions.