Course contentsShow
← TypeScript
Lesson 1349 of 1,79631. Type-Driven DesignFree lesson

The Substitution Problem

Why structurally identical primitives like UserId and ProductId can be accidentally swapped without type errors.

The Substitution Problem

What you'll learn: Why TypeScript's structural type system allows you to accidentally swap semantically different values that happen to share the same shape.


In TypeScript, types are checked by their structure (shape), not their name. This is called structural typing. While incredibly flexible, it creates a subtle danger: two types with identical structure are considered interchangeable, even when they represent completely different concepts in your domain.

The Core Issue

Imagine you're building an e-commerce system with user IDs and product IDs:

type UserId = string;
type ProductId = string;

function getUser(id: UserId): void {
  console.log(`Fetching user ${id}`);
}

function getProduct(id: ProductId): void {
  console.log(`Fetching product ${id}`);
}

const userId: UserId = "user-123";
const productId: ProductId = "prod-456";

// This compiles just fine, but it's wrong!
getUser(productId); // No error! ❌
getProduct(userId); // No error! ❌

TypeScript sees both UserId and ProductId as string, so it considers them substitutable. You can pass a ProductId where a UserId is expected, and the compiler won't complain. This is the substitution problem in action.

Why This Happens

TypeScript uses structural equivalence: if two types have the same structure, they're the same type. Since both UserId and ProductId are just string, structurally they're identical.

The Real-World Impact

This seemingly small issue can cause serious bugs: fetching the wrong record from a database, mixing up foreign keys, processing the wrong entity. The type system can't help because, to TypeScript, these are the same type.

Key Takeaway: Structural typing means primitives like strings or numbers can't distinguish between semantically different concepts—they're all substitutable based on shape alone, creating opportunities for silent bugs in your domain logic.