Overview
Thez.coerce namespace provides utilities for automatic type conversion. Coercion schemas attempt to convert input values to the target type before validation, making it easier to work with form data, query parameters, and other loosely-typed inputs.
Available Coercions
z.coerce.string()
Converts any input to a string using JavaScript’sString() function.
string | ZodStringParams
Optional error message or configuration object
ZodCoercedString
z.coerce.number()
Converts input to a number using JavaScript’sNumber() function.
string | ZodNumberParams
Optional error message or configuration object
ZodCoercedNumber
z.coerce.boolean()
Converts input to a boolean using JavaScript’sBoolean() function.
string | ZodBooleanParams
Optional error message or configuration object
ZodCoercedBoolean
Note that
z.coerce.boolean() uses JavaScript’s truthiness rules. The string "false" coerces to true because it’s a non-empty string. For parsing string booleans, use z.stringbool() instead.z.coerce.bigint()
Converts input to a BigInt using JavaScript’sBigInt() function.
string | ZodBigIntParams
Optional error message or configuration object
ZodCoercedBigInt
z.coerce.date()
Converts input to a Date object using JavaScript’sDate() constructor.
string | ZodDateParams
Optional error message or configuration object
ZodCoercedDate
Common Use Cases
Form Data
Coercion is particularly useful when parsing form data, where all values arrive as strings:Query Parameters
CSV Parsing
Chaining with Validators
Coercion happens before validation, so you can chain validation methods:Type Inference
Coerced schemas maintain proper TypeScript types:Validation Errors
Coercion failures result in validation errors:Comparison with Transform
Coercion is different from.transform():
- Coercion happens before validation and is lossy (information may be lost)
- Transform happens after validation and should be lossless
Best Practices
Use coercion for external inputs
Coercion is ideal for data from external sources like forms, URLs, and APIs where types aren’t guaranteed.
Validate after coercion
Always add validation after coercion to ensure the coerced value meets your requirements.
Be aware of edge cases
Test edge cases like empty strings, null, undefined, and special values (NaN, Infinity) to understand coercion behavior.
Consider alternatives
For strict type checking without coercion, use regular schemas. For custom conversions, use
.transform() or .pipe().