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.

TypescriptForm Validation

Code

typescriptsnippet
17 lines
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.success exits the flow early through return when 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

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.