Building a Schema-First API Response Type
What you'll learn: How to define a Zod schema for API responses and automatically derive the TypeScript type from it as your single source of truth.
The Schema-First Philosophy
In the previous lessons, you saw how to infer types from schemas. Now we'll apply that pattern to build API response types where the schema comes first and the TypeScript type follows automatically.
The key idea: write your validation schema once, infer the type from it. This eliminates the duplication of defining both a type and a validator separately.
Building Your First Schema-First Response Type
Here's the pattern:
import { z } from 'zod';
// Schema first - this is your source of truth
const UserResponseSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string(),
isActive: z.boolean()
});
// Type derived automatically
type UserResponse = z.infer<typeof UserResponseSchema>;
// Now use both in your API call
async function fetchUser(id: number): Promise<UserResponse> {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
// Runtime validation
const validated = UserResponseSchema.parse(data);
// TypeScript knows the exact shape
return validated;
}
The schema defines both the runtime validation rules and the compile-time type. You maintain one thing, not two.
Why This Matters
Without schema-first, you'd write the type separately from your validation logic, risking drift between what you say the API returns and what you actually validate at runtime. Schema-first keeps them synchronized automatically.
Key Takeaway: Define Zod schemas as your single source of truth for API responses, then use z.infer<typeof Schema> to extract the TypeScript type—eliminating duplication and guaranteeing your types match your runtime checks.