DEV Community

Cover image for Understanding Intersection Types in TypeScript
Fabio J Raminhuk
Fabio J Raminhuk

Posted on

Understanding Intersection Types in TypeScript

Introduction

Intersection types are an essential feature in TypeScript that allow developers to combine multiple types into a single type. This powerful tool enhances type safety and flexibility in codebases. In this article, we'll delve into what intersection types are, how they work, and explore some practical use cases in TypeScript.

What are Intersection Types?

Intersection types in TypeScript are denoted by the & symbol and are used to combine multiple types into a single type that has all the features of each constituent type. When a value is of an intersection type, it must satisfy all the types included in the intersection.

Syntax:

type CombinedType = Type1 & Type2;
Enter fullscreen mode Exit fullscreen mode

Example:

type Dog = {
  name: string;
  breed: string;
};

type Bird = {
  name: string;
  wingspan: number;
};

type Pet = Dog & Bird;

const myPet: Pet = {
  name: "Charlie",
  breed: "Labrador",
  wingspan: 30,
};
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Extending Object Types:

Intersection types are useful when extending object types with additional properties while retaining the original properties.

type User = {
  id: number;
  name: string;
};

type Admin = {
  id: number;
  role: string;
};

type SuperAdmin = User & Admin;

const superAdminUser: SuperAdmin = {
  id: 1,
  name: "John Doe",
  role: "Super Admin",
};
Enter fullscreen mode Exit fullscreen mode

Combining Function Signatures:

Intersection types can combine multiple function signatures, allowing functions to accept different parameter types or return multiple types.

type Logger = (message: string) => void;
type Formatter = (message: string) => string;

type LogFormatter = Logger & Formatter;

const logAndFormat: LogFormatter = (message) => {
  console.log(message);
  return `Formatted: ${message}`;
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

Intersection types in TypeScript provide a powerful mechanism for creating complex types by combining multiple types. They offer enhanced type safety and flexibility, enabling developers to express richer data structures and function signatures in their code.

Explore more about TypeScript's intersection types and unleash their potential in your projects!

References:
Understanding Intersection Types in TypeScript
Intersection Types

Top comments (0)