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

The Problem: Primitive Obsession

Understand how using raw primitives for domain concepts leads to mixing incompatible values.

The Problem: Primitive Obsession

You'll learn why using raw primitive types like string and number for domain-specific values creates subtle bugs that compile successfully but fail at runtime.

What Is Primitive Obsession?

Primitive obsession is when you represent domain concepts using basic types like string, number, or boolean instead of creating distinct types for each concept. This seems convenient at first—after all, a user ID is just a string, right?

The danger appears when you have multiple string-based concepts in the same system. A user ID is a string. An order ID is a string. An email address is a string. TypeScript sees them all as identical and interchangeable, even though mixing them up would be a serious bug.

The Classic Example

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

function getOrder(orderId: string): void {
  console.log(`Fetching order ${orderId}`);
}

const userId = "user_12345";
const orderId = "order_67890";

// This is fine
getUser(userId);

// This compiles perfectly but is completely wrong!
getUser(orderId);  // No error—both are just strings

TypeScript's type checker is perfectly happy with this code. Both userId and orderId are strings, so passing an order ID where a user ID is expected type-checks successfully. The bug only surfaces at runtime when you fetch the wrong data.

Why This Happens

When everything is string or number, you lose TypeScript's greatest strength: distinguishing between different kinds of data. The type system can't help you because you've told it that all these values are the same type.

This is especially dangerous in functions with multiple parameters of the same primitive type—parameter order mistakes become invisible:

function transfer(fromAccount: string, toAccount: string, amount: number): void {
  // Implementation
}

// Easy to accidentally swap these!
transfer(toAccount, fromAccount, 100);  // TypeScript sees nothing wrong

Key Takeaway: Using raw primitives for domain concepts means TypeScript cannot distinguish between semantically different values, allowing you to mix incompatible data without any compile-time errors.