Type coercion in Zod
Coercion converts input data to the type a schema expects. Use z.coerce in place of z to get the coercing version of a primitive schema.
How it works
- Use z.coerce instead of z.
z.coerce.string()is used in place ofz.string(). The code parses a string, a number, a boolean andnulland prints each result. [1] - Convert to numbers and booleans.
z.coerce.number()parses values like"42"and"3.5", and the code prints each value with itstypeof.z.coerce.boolean()parses several values, including the string"false", and prints what comes out. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import * as z from "zod";
const str = z.coerce.string();
for (const v of ["tuna", 42, true, null]) {
const out = str.parse(v);
console.log(`coerce.string(${JSON.stringify(v)}) ->`, JSON.stringify(out));
}
const num = z.coerce.number();
for (const v of ["42", "3.5", true]) {
const out = num.parse(v);
console.log(`coerce.number(${JSON.stringify(v)}) ->`, out, `(${typeof out})`);
}
const bool = z.coerce.boolean();
for (const v of ["yes", "false", "", 0, 1]) {
console.log(`coerce.boolean(${JSON.stringify(v)}) ->`, bool.parse(v));
}
The boolean lines print what z.coerce.boolean() returns for each value, including the string "false". Code written by AgentGid [1].
The boolean lines print what z.coerce.boolean() returns for each value, including the string "false". Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with zod 4.6.6. Needs WebGL.
More Zod examples
Handling errors with ZodError in Zod String formats in Zod: email, UUID, phone, datetime String validation in Zod Literal values in Zod
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.