Deriving Frontend Types from Backend Schemas
You'll learn: How to define a single schema using libraries like Zod that automatically provides both runtime validation and TypeScript types, eliminating duplication between backend and frontend.
The Single Source of Truth
When you define a schema with Zod or similar libraries, you're creating a runtime validator that doubles as a type definition. Instead of writing a TypeScript interface for your frontend and separate validation logic for your backend, you write one schema that serves both purposes.
Think of it like writing a blueprint that's simultaneously read by construction workers (runtime validation) and architects (TypeScript compiler). One document, two audiences.
How It Works
import { z } from 'zod';
// Define the schema ONCE
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
age: z.number().optional(),
});
// Derive the TypeScript type
type User = z.infer<typeof UserSchema>;
// Now you have both:
// 1. Runtime validation: UserSchema.parse(data)
// 2. Compile-time type: User
The schema validates incoming data at runtime, catching bad API responses. The inferred User type gives you autocomplete and type-checking throughout your frontend code. No manual synchronization needed.
The Power of Inference
When you update the schema—say, making age required—the TypeScript type automatically updates everywhere it's used. Your IDE immediately highlights every place that needs updating. The schema and types can never drift apart because they're the same thing.
Key Takeaway: Using Zod's z.infer<typeof Schema>, you define validation rules once and automatically derive TypeScript types, ensuring your runtime checks and compile-time types always match.