Intersection and union types are two powerful features in TypeScript that allow you to create more flexible and robust types for your code. In this tutorial, we'll take a closer look at what these types are, how they work, and how you can use them in your TypeScript code.


What are Intersection Types?

An intersection type in TypeScript is a way of combining multiple types into a single type. This is done using the & symbol. For example, suppose you have two interfaces defined as follows:

interface Employee {
  name: string;
  age: number;
}

interface Manager {
  department: string;
  reports: number[];
}


You can create a new type that represents an employee who is also a manager using the intersection type as follows:

type ManagerEmployee = Employee & Manager;

Now, ManagerEmployee type has all the properties of both Employee and Manager interfaces.

const john: ManagerEmployee = {
  name: 'John',
  age: 35,
  department: 'Sales',
  reports: [1, 2, 3],
};


What are Union Types?

A union type in TypeScript is a way of creating a type that can be one of several types. This is done using the | symbol. For example, suppose you have two interfaces defined as follows:

interface Square {
  kind: 'square';
  size: number;
}

interface Circle {
  kind: 'circle';
  radius: number;
}

You can create a new type that represents either a square or a circle using the union type as follows:

type Shape = Square | Circle;

Now, Shape type can either be of type Square or Circle.

function area(shape: Shape) {
  switch (shape.kind) {
    case 'square':
      return shape.size ** 2;
    case 'circle':
      return Math.PI * shape.radius ** 2;
  }
}


Intersection Types vs. Union Types

Intersection types and union types are similar in that they both allow you to combine types. However, they are used for different purposes.

Intersection types are used to create a type that has all the properties of two or more types. This is useful when you want to create a new type that has the features of multiple existing types.

Union types, on the other hand, are used to create a type that can be one of several types. This is useful when you want to create a type that can have multiple possible shapes, such as with the Shape example above.


Conclusion

Intersection and union types are powerful tools in TypeScript that allow you to create more flexible and robust types for your code. By combining multiple types into a single type or creating a type that can be one of several types, you can make your code more expressive and easier to understand.