Intersection types in Typescript

Intersection Types in TypeScript are denoted by the & symbol and are used to combine multiple types into one. When two or more types are intersected, the resulting type contains all properties and methods of each individual type.

Let's start with a simple User object which has his personal information. We can define a interface like below

interface User {
  id: number;
  name: string;
  email: string;
}

Now we want to extend it to add address. We can do

interface User {
  id: number;
  name: string;
  email: string;
  street: string;
  city: string;
  zipCode: string;
}

Although we could create a single object with both user and address data, doing so might lead to a monolithic and less maintainable data structure. Intersection allows us separating concerns into smaller, focused pieces (like User and Address).

 // User interface representing user data
interface User {
  id: number;
  name: string;
  email: string;
}

// Address interface representing user address
interface Address {
  street: string;
  city: string;
  zipCode: string;
}

// Intersection type of User and Address
type UserWithAddress = User & Address;

// Example user data
const userWithAddress: UserWithAddress = {
  id: 1,
  name: "John Doe",
  email: "john@example.com",
  street: "123 Main St",
  city: "New York",
  zipCode: "10001",
};

In this example, we have two interfaces: User, which contains data about a user, and Address, which holds information about the user's address. Now, we want to combine these two interfaces into a new type called UserWithAddress. This type will include all the properties from both User and Address, giving us a user object that also has additional address information.

TypeScriptIntersection TypesTypes In TypescriptJavaScript
Avatar for sanket-s10

Written by sanket-s10

Frontend Developer | Skilled in JavaScript, TypeScript, ReactJS, NextJS | Dedicated to creating elegant and intuitive user interfaces

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.