runtime.boot

Full Stack Systems
Production Mindset

CodeWithMihir

Engineering thoughtful products from interface to infrastructure.

CodeWithMihir

TypeScript Tutorial

TypeScript Intersection Types Explained

Learn how intersection types work in TypeScript, including combining object types, reusable model composition, and common mistakes.

Welcome back! I am Mihir, and in this lesson we will learn intersection types in TypeScript.

An intersection type combines multiple types into one type using &.


Basic Intersection Type

type HasName = {
  name: string;
};

type HasEmail = {
  email: string;
};

type User = HasName & HasEmail;

User must have both properties.

const user: User = {
  name: "Mihir",
  email: "mihir@example.com",
};

Intersection Means All Requirements

This is invalid:

const user: User = {
  name: "Mihir",
};

email is missing.

An intersection means the value must satisfy every combined type.


Combining with Extra Fields

type BaseEntity = {
  id: number;
  createdAt: Date;
};

type Product = BaseEntity & {
  name: string;
  price: number;
};

Usage:

const product: Product = {
  id: 1,
  createdAt: new Date(),
  name: "Keyboard",
  price: 2500,
};

Practical Example: API Response

type SuccessResponse = {
  success: true;
};

type UserData = {
  user: {
    id: number;
    name: string;
  };
};

type UserResponse = SuccessResponse & UserData;

UserResponse includes both the status and the data.


Intersection with Function Types

You can also combine callable types with properties, though this is less common.

type Counter = {
  (): number;
  reset(): void;
};

This describes a function that can be called and also has a reset method.


Conflicting Property Types

Be careful when two types define the same property differently.

type A = {
  id: number;
};

type B = {
  id: string;
};

type C = A & B;

The id property becomes impossible to use because it would need to be both number and string.

In practice, avoid conflicting intersections.


Intersection vs Union

Union means one of several possibilities:

type Id = string | number;

Intersection means all combined requirements:

type AdminUser = User & {
  role: "admin";
};

The symbols are small, but the meaning is very different.


Quick Recap

  • Intersection types use &.
  • They combine multiple type requirements into one type.
  • They are useful for composing reusable object models.
  • Avoid conflicting property types.
  • Do not confuse intersections with unions.

Next up, we will learn Index Signatures → for objects with dynamic keys.