Zod Schema With Inferred Type
Define a validation schema once with Zod and derive the TypeScript type from it, so runtime checks and compile-time types never drift apart.
Code
import { z } from "zod";
export const SignupSchema = z.object({
email: z.string().email(),
password: z.string().min(12),
age: z.number().int().min(13).optional(),
});
export type Signup = z.infer<typeof SignupSchema>;
export function parseSignup(input: unknown) {
const parsed = SignupSchema.safeParse(input);
if (!parsed.success) {
return { valid: false as const, issues: parsed.error.issues };
}
return { valid: true as const, data: parsed.data };
}Report a problem with this exampleOpens a pre-filled issue on GitHub.