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 schemaValidate string.
import { z } from 'zod';
const Schema = z.string();
Schema.parse('Alice');
Object schemaDefine object shape.
const User = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().optional(),
});
Enum schemaAllowed values.
const Role = z.enum(['admin', 'user', 'guest']);

Composition

Union schemaMatch 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 parseParse without throwing.
const result = User.safeParse(input);
if (!result.success) { console.log(result.error.format()); }

Type Inference

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

Transformation

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

Advanced

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