Normalize numeric input
A form field supplies a numeric value as text, but application logic requires a number.
Zod · Const
z.coerce provides primitive schemas that first convert unknown input with JavaScript constructors, then validate the converted value. Documented variants cover strings, numbers, booleans, and bigints.
z.coerce provides coercing versions of several primitive schemas. Each variant first converts the input using the corresponding JavaScript constructor, then validates the converted result as that primitive type; in current Zod, coerced schemas accept unknown input.
z.coerce.string();
z.coerce.number();
z.coerce.boolean();
z.coerce.bigint();A coercing Zod schema for the selected primitive type.
z.coerce namespace when input needs conversion into a primitive type before validation.z.coerce.string() converts its input with JavaScript's String constructor.z.coerce.number() uses JavaScript's Number conversion and returns a number schema.z.coerce.boolean() applies JavaScript's Boolean conversion to the input.z.coerce.bigint() applies JavaScript's BigInt conversion to the input.unknown, rather than the primitive type being produced.import { z } from "zod";
const schema = z.coerce.number();
console.log(schema.parse("42")); // 42
console.log(schema.parse(7)); // 7The schema converts inputs with JavaScript's Number conversion before validating the resulting number.
A form field supplies a numeric value as text, but application logic requires a number.
A query parameter or environment value must become a validated primitive before use.
An API boundary accepts primitive values in varying representations and needs a consistent output type.
z.coerce do?z.coerce creates schemas that convert input to a target primitive before validation. For example, z.coerce.number() applies Number(input), while the other documented variants use the corresponding constructor.
Follow-up: What is the input type of a coerced schema in current Zod? It is unknown, even though parsing produces the target primitive type.
The documented variants are string, number, boolean, and bigint. Each returns a schema whose parsing process attempts to convert the input to that type.
Follow-up: How would you handle an omitted coerced object property? Declare the fallback explicitly with .default() rather than relying on coercion.
Coercion is useful when external data arrives in a different representation, such as a numeric string from a form or query parameter. The resulting schema still validates the converted value as the requested primitive.
Follow-up: What changed for missing object keys in current Zod? A missing key on an object field using z.coerce.* now produces an error unless the field is made optional or given an explicit default.
z.stringz.numberz.booleanz.bigint