Coercion
Coercion for primitives
Zod now provides a more convenient way to coerce primitive values.
const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
During the parsing step, the input is passed through the String()
function, which is a JavaScript built-in for coercing data into strings.
schema.parse(12); // => "12"
schema.parse(true); // => "true"
schema.parse(undefined); // => "undefined"
schema.parse(null); // => "null"
The returned schema is a normal ZodString
instance so you can use all string methods.
z.coerce.string().email().min(5);
How coercion works
All primitive types support coercion. Zod coerces all inputs using the built-in constructors: String(input)
, Number(input)
, new Date(input)
, etc.
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)
Note: — Boolean coercion with z.coerce.boolean()
may not work how you expect. Any truthy value is coerced to true
, and any falsy value is coerced to false
.
const schema = z.coerce.boolean(); // Boolean(input)
schema.parse("tuna"); // => true
schema.parse("true"); // => true
schema.parse("false"); // => true
schema.parse(1); // => true
schema.parse([]); // => true
schema.parse(0); // => false
schema.parse(""); // => false
schema.parse(undefined); // => false
schema.parse(null); // => false
For more control over coercion logic, consider using z.preprocess
or z.pipe()
.