docs
guides
reference
TypeScript-first schema validation library with static type inference. Define schemas, validate data, and get type safety with zero dependencies.
import * as z from 'zod';
// Define a schema
const User = z.object({
name: z.string(),
age: z.number().int().positive(),
email: z.string().email(),
});
// Parse and validate
const user = User.parse({ name: 'Alice', age: 30, email: 'alice@example.com' });
// Safe parsing (no throw)
const result = User.safeParse({ name: 'Bob', age: 25 });
if (result.success) {
console.log(result.data);
} else {
console.error(result.error.issues);
}
// Type inference
type User = z.infer<typeof User>;z.string(), z.object(), etc.)parse() (throws) or safeParse() (returns result)z.infer<T>z.string().min(3).email()transform() and refine()z.string() // String validator
z.number() // Number validator
z.boolean() // Boolean validator
z.date() // Date validator
z.bigint() // BigInt validator
z.null() // Null validator
z.undefined() // Undefined validator
z.any() // Accepts any value
z.unknown() // Unknown type
z.never() // Always failsz.object({ ... }) // Object schema
z.array(schema) // Array schema
z.tuple([...]) // Tuple schema
z.record(key, value) // Record/dictionary
z.map(key, value) // Map schema
z.set(value) // Set schema
z.enum([...]) // Enum schema
z.union([...]) // Union schema
z.intersection(a, b) // Intersection schema.optional() // Make optional
.nullable() // Accept null
.nullish() // Accept null or undefined
.default(value) // Provide default
.catch(value) // Catch errors
.readonly() // Make readonly
.brand<T>() // Add type brandschema.parse(data) // Parse (throws on error)
schema.safeParse(data) // Safe parse (returns result)
schema.parseAsync(data) // Async parse
schema.safeParseAsync(data) // Async safe parsez.infer<typeof schema> // Extract output type
z.output<typeof schema> // Extract output type (alias)
z.input<typeof schema> // Extract input typeconst FormSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
age: z.number().int().min(18),
});
const result = FormSchema.safeParse(formData);const ApiRequest = z.object({
userId: z.string().uuid(),
action: z.enum(['create', 'update', 'delete']),
data: z.record(z.string(), z.any()),
});const EnvSchema = z.object({
PORT: z.coerce.number().int().min(1).max(65535),
DATABASE_URL: z.string().url(),
DEBUG: z.coerce.boolean().default(false),
});
const env = EnvSchema.parse(process.env);try {
const data = schema.parse(input);
} catch (error) {
if (error instanceof z.ZodError) {
// Handle validation errors
console.error(error.issues);
console.error(error.format());
console.error(error.flatten());
}
}npm install zodzod