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 };
}What the snippet does
Zod Schema With Inferred Type keeps everything in the function parseSignup.
z are the only symbols borrowed from zod — the coupling is explicit and narrow.
The result comes back as an object carrying const.
What to watch for
- External dependency:
zod— install it before running the snippet. - The guard
!parsed.successexits the flow early throughreturnwhen its condition holds.
Using it
The entry point signature is export const SignupSchema =
SignupSchema is what another module would consume; nothing else here is load-bearing for callers.
The call returns const.
Key statements
return { valid: false as const, issues: parsed.error.issues };
return { valid: true as const, data: parsed.data };
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `SignupSchema` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- What does this need from the package registry?
- These are real dependencies: `zod`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.