The Problem: Duplication Between Runtime and Type Checks
You'll learn why maintaining separate validation logic and TypeScript types creates a maintenance nightmare and how easy it is for them to drift apart.
The Two Worlds Problem
TypeScript lives in two separate worlds, and they don't talk to each other:
- Compile-time types — TypeScript checks your code before it runs
- Runtime validation — Your code checks data when it actually executes
The problem? You have to write the same rules twice.
A Common Scenario
Imagine you're building an API endpoint that accepts user registration data. You need:
- A TypeScript interface so your code knows what shape to expect
- Runtime validation to ensure the actual incoming data matches that shape
Without a tool like Zod, you write both manually:
// TypeScript interface (compile-time only)
interface UserRegistration {
email: string;
age: number;
username: string;
}
// Runtime validation (actual JavaScript code)
function validateUserRegistration(data: unknown): data is UserRegistration {
if (typeof data !== 'object' || data === null) return false;
const obj = data as Record<string, unknown>;
return (
typeof obj.email === 'string' &&
typeof obj.age === 'number' &&
typeof obj.username === 'string'
);
}
The Maintenance Burden
Now your product manager says: "Make age optional." You must update both places:
// Update 1: The interface
interface UserRegistration {
email: string;
age?: number; // Added ?
username: string;
}
// Update 2: The validator
function validateUserRegistration(data: unknown): data is UserRegistration {
if (typeof data !== 'object' || data === null) return false;
const obj = data as Record<string, unknown>;
return (
typeof obj.email === 'string' &&
(obj.age === undefined || typeof obj.age === 'number') && // Changed
typeof obj.username === 'string'
);
}
Miss one? Your types lie. Your validation catches things TypeScript allows, or vice versa.
Why This Happens
Think of it like writing the same recipe in two languages — one for you to plan with, one for the actual cooking. Every time you adjust ingredients, you must translate again. Forget once, and the dish doesn't match the plan.
The duplication exists because:
- TypeScript types disappear after compilation
- Runtime data from networks, files, or users needs actual JavaScript checks
- There's no automatic bridge between the two
Key Takeaway: Maintaining separate TypeScript types and runtime validators leads to inevitable drift, bugs, and double the maintenance work — which is exactly why libraries that generate types from schemas (or vice versa) have become essential for type-safe APIs.