Primitives
Zod provides validators for all JavaScript primitive types.
Basic Types
ts
import { z } from "zod";
// Primitive value types
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// Empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// Catch-all types
z.any();
z.unknown();
// Never type
z.never();
Type Coercion
Zod provides a convenient way to coerce primitive types:
ts
const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
schema.parse(true); // => "true"
// All primitive types support coercion
z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)
Boolean Coercion
Boolean coercion is straightforward:
ts
z.coerce.boolean().parse("tuna"); // => true
z.coerce.boolean().parse("true"); // => true
z.coerce.boolean().parse("false"); // => true
z.coerce.boolean().parse(1); // => true
z.coerce.boolean().parse([]); // => true
z.coerce.boolean().parse(0); // => false
z.coerce.boolean().parse(undefined); // => false
z.coerce.boolean().parse(null); // => false
Custom Error Messages
You can customize error messages when creating schemas:
ts
const name = z.string({
required_error: "Name is required",
invalid_type_error: "Name must be a string",
});
const age = z.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number",
});