Intersection Types

Introduction to Intersection Types

Intersection types are created with the & operator. Intersection behaves differently if used with literal types vs object types. The & operator behaves like an and operation for literal types, but as an union operation for object types.

Intersection of non non-object types

type T = string & number;
// type T = never

The resulting type is never because T cannot possibly be both string and number. In this case, the name “intersection” makes sense. There is no intersection between string and number. There is no value that is both a string and a number.

Intersection of object types

However, this creates an union of the type constituents:

type BaseConfig = {
  url: string;
  version: number;

type U = BaseConfig & { headers: Record<string, string> };
// type U = BaseConfig & {
//   headers: Record<string, string>;
// }

Intersection type for config object with intellisense

It is as if we had done this:

type U = {
  url: string;
  version: number;
  headers: Record<string, string>;

In this case, & really behaves like an union of the type constituents, not like an intersection.