Course contentsShow
← TypeScript
Lesson 450 of 1,79610. Intersection TypesFree lesson

Extending Base Types with Capabilities

Use intersections to add optional capabilities or metadata fields to existing types without modifying them.

Extending Base Types with Capabilities

You'll learn how to add optional features or metadata to existing types using intersections, without permanently modifying the original type definitions.

The Core Idea

Imagine you have a User type that works perfectly for basic operations. Now you need the same user data, but with tracking metadata for analytics, or optional admin capabilities for privileged users. Instead of creating completely new types or changing User, you can extend it using intersections.

This is like attaching accessories to a base model. The original remains unchanged, but you get enhanced versions when needed.

How It Works

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

// Add optional tracking capabilities
type Timestamped = {
  createdAt?: Date;
  updatedAt?: Date;
};

type TrackedUser = User & Timestamped;

const user: TrackedUser = {
  id: 1,
  name: "Alice",
  createdAt: new Date() // optional, but available
};

You can stack multiple capability layers:

type Auditable = {
  lastModifiedBy?: string;
  version?: number;
};

type FullyTrackedUser = User & Timestamped & Auditable;

const adminUser: FullyTrackedUser = {
  id: 2,
  name: "Bob",
  createdAt: new Date(),
  lastModifiedBy: "system",
  version: 1
};

Why This Matters

This pattern keeps your base types clean and composable. User remains simple for basic use cases, but you can enhance it contextually—for database operations, API responses, or admin interfaces—without fragmentation.

Key Takeaway: Use intersections to compose types by adding optional capabilities or metadata fields, keeping base types minimal while enabling rich, context-specific variants.