Type-Safe IDs and Handles
What you'll learn: How to use opaque types to prevent accidentally mixing different kinds of identifiers like user IDs and product IDs.
The Problem: All IDs Look the Same
When your application uses IDs for different entities, TypeScript sees them all as the same primitive type:
type UserId = string;
type ProductId = string;
type OrderId = string;
function getUser(id: UserId) { /* ... */ }
function getProduct(id: ProductId) { /* ... */ }
const userId: UserId = "user_123";
const productId: ProductId = "prod_456";
// TypeScript allows this mistake!
getUser(productId); // No error - both are just strings
getProduct(userId); // No error - disaster waiting to happen
Since all three are just string, TypeScript considers them interchangeable. You can pass a ProductId where a UserId is expected, and the type system won't catch it.
The Solution: Opaque ID Types
Apply the branding technique to create distinct, incompatible ID types:
declare const UserIdBrand: unique symbol;
type UserId = string & { [UserIdBrand]: true };
declare const ProductIdBrand: unique symbol;
type ProductId = string & { [ProductIdBrand]: true };
declare const OrderIdBrand: unique symbol;
type OrderId = string & { [OrderIdBrand]: true };
function getUser(id: UserId) { /* ... */ }
function getProduct(id: ProductId) { /* ... */ }
const userId = "user_123" as UserId;
const productId = "prod_456" as ProductId;
getUser(productId); // ❌ Error: ProductId is not assignable to UserId
getProduct(userId); // ❌ Error: UserId is not assignable to ProductId
Now each ID type is structurally unique. TypeScript will catch any attempt to mix them.
Smart Constructors for Safety
Combine validation with type creation:
function createUserId(raw: string): UserId {
if (!raw.startsWith("user_")) {
throw new Error("Invalid UserId format");
}
return raw as UserId;
}
function createProductId(raw: string): ProductId {
if (!raw.startsWith("prod_")) {
throw new Error("Invalid ProductId format");
}
return raw as ProductId;
}
// Safe creation with validation
const safeUserId = createUserId("user_123"); // ✓
const safeProductId = createProductId("prod_456"); // ✓
getUser(safeProductId); // Still caught at compile time!
Real-World Pattern: API Handles
This pattern shines when handling external identifiers:
declare const SessionTokenBrand: unique symbol;
type SessionToken = string & { [SessionTokenBrand]: true };
declare const ApiKeyBrand: unique symbol;
type ApiKey = string & { [ApiKeyBrand]: true };
function authenticate(token: SessionToken) { /* ... */ }
function authorizeApiCall(key: ApiKey) { /* ... */ }
// Cannot accidentally use an API key as a session token
Key Takeaway: Opaque types with branding prevent identifier mix-ups by making structurally identical primitives incompatible, catching logic errors at compile time before they reach production.