We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie zod-guide

Zod Guide

[validation][typescript][schemas]
JavaScript / TypeScript
Install
npm install zod

Zod fills the gap between TypeScript's compile-time types and runtime reality.

Define schema once and derive the TypeScript type: changing the schema updates both.

Zod composes: extend schemas, transform values, create discriminated unions.

Basic Schemas

String schema· Validate string.
import { z } from 'zod';
const Schema = z.string();
Schema.parse('Alice');
Object schema· Define object shape.
const User = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().optional(),
});
Enum schema· Allowed values.
const Role = z.enum(['admin', 'user', 'guest']);

Composition

Union schema· Match one of several.
const Result = z.discriminatedUnion('status', [
  z.object({ status: z.literal('success'), data: z.any() }),
  z.object({ status: z.literal('error'), message: z.string() }),
]);

Parsing

Safe parse· Parse without throwing.
const result = User.safeParse(input);
if (!result.success) { console.log(result.error.format()); }

Type Inference

Infer type· Derive TS type from schema.
type User = z.infer<typeof User>;
// { name: string; email: string; age?: number }

Transformation

Transform· Parse then transform output.
const Slug = z.string().transform(s => s.toLowerCase().replace(/\s+/g, '-'));
Default· Default when undefined.
const Config = z.object({ port: z.coerce.number().default(3000), host: z.string().default('localhost') });

Advanced

Refine· Custom validation.
const Password = z.string().min(8).refine(v => /[A-Z]/.test(v), 'Need uppercase');
Env validation· Validate process.env.
const Env = z.object({
  DATABASE_URL: z.string().url(),
  NODE_ENV: z.enum(['development', 'production']),
});
export const env = Env.parse(process.env);