Typed Form Validation with Inferred Schemas
What you'll learn: How to automatically keep your form data types perfectly synchronized with your validation schemas using type inference.
The Synchronization Problem
When building forms, you typically need:
- Validation rules - runtime checks to ensure data is correct
- TypeScript types - compile-time types for your form data
Writing these separately creates two sources of truth that can drift apart. Change your validation schema? You must remember to update your types. Miss it, and TypeScript won't catch the mismatch.
Schema Inference as the Solution
Modern validation libraries let you write the schema once and infer the TypeScript type from it. The schema becomes your single source of truth:
import { z } from 'zod';
// Define your schema
const userFormSchema = z.object({
username: z.string().min(3),
email: z.string().email(),
age: z.number().int().positive().optional(),
});
// Infer the TypeScript type automatically
type UserFormData = z.infer<typeof userFormSchema>;
// Result: { username: string; email: string; age?: number | undefined }
Now when you change the schema (e.g., make age required), the type updates automatically. You use UserFormData in your component props, state, and handlers—TypeScript will immediately flag any mismatches.
Practical Pattern
function handleSubmit(data: UserFormData) {
// data is fully typed based on schema
console.log(data.username); // ✓ known to exist
console.log(data.age?.toFixed()); // ✓ correctly optional
}
const result = userFormSchema.safeParse(formInput);
if (result.success) {
handleSubmit(result.data); // perfectly typed
}
Key Takeaway: Infer form data types from validation schemas to maintain a single source of truth, eliminating sync bugs between runtime validation and compile-time types.