Zod Basics: Defining Schemas
You'll learn: How to create simple Zod schemas to define the shape and types of your form data at runtime.
What is a Zod Schema?
Think of a Zod schema as a blueprint for your data. Just like TypeScript types check your code at compile time, Zod schemas validate your data at runtime. This is crucial for forms because user input arrives at runtime and could be anything.
A schema describes what valid data looks like: which fields exist, what type each field should be, and what constraints apply.
Creating Basic Schemas
Zod provides simple building blocks that mirror TypeScript types:
import { z } from 'zod';
// Define a user registration schema
const userSchema = z.object({
username: z.string(),
age: z.number(),
email: z.string()
});
Here, z.object() creates an object schema with specific fields. Each field uses a primitive schema like z.string() or z.number().
Schema Inference
The magic happens when Zod automatically infers TypeScript types from your schema:
type User = z.infer<typeof userSchema>;
// TypeScript now knows: { username: string; age: number; email: string }
You write the schema once, and TypeScript understands both the runtime validation rules AND the compile-time types. No duplicate type definitions needed!
Why This Matters for Forms
When a form submits, you receive plain JavaScript values. Without validation, you're trusting the user completely. Zod schemas let you verify the data matches your expectations before processing it, catching type mismatches, missing fields, or malformed inputs immediately.
Key Takeaway: Zod schemas use z.object(), z.string(), and z.number() to define data structures that validate at runtime and automatically generate TypeScript types via z.infer.