Skip to main content

Overview

The z.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’s String() function.
string | ZodStringParams
Optional error message or configuration object
Returns: ZodCoercedString

z.coerce.number()

Converts input to a number using JavaScript’s Number() function.
string | ZodNumberParams
Optional error message or configuration object
Returns: ZodCoercedNumber

z.coerce.boolean()

Converts input to a boolean using JavaScript’s Boolean() function.
string | ZodBooleanParams
Optional error message or configuration object
Returns: 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’s BigInt() function.
string | ZodBigIntParams
Optional error message or configuration object
Returns: ZodCoercedBigInt
Invalid BigInt conversions throw native JavaScript errors, not ZodErrors. This is a limitation of the BigInt constructor.

z.coerce.date()

Converts input to a Date object using JavaScript’s Date() constructor.
string | ZodDateParams
Optional error message or configuration object
Returns: 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:
You can override the input type if needed:

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().

See Also

  • Transform - Custom data transformations
  • Pipe - Chain schemas together
  • String - String validation
  • Number - Number validation