Capítulo 12 de 61

Chapter 12: Stringbools

Core Idea

z.stringbool() (Zod 4+) converts "boolish" strings like "true", "1", "yes", "on" into a real boolean, which is the common case when parsing environment variables or form data.

Key Concepts

  • z.stringbool(): parses recognized truthy/falsy strings into true/false; anything else throws an invalid_value error.
  • Default truthy set: ["true", "1", "yes", "on", "y", "enabled"].
  • Default falsy set: ["false", "0", "no", "off", "n", "disabled"].
  • { truthy, falsy }: override the accepted value lists.
  • { case: "sensitive" }: opts out of the default case-insensitive matching (inputs are lowercased before comparison by default).

Code Examples

const strbool = z.stringbool();

strbool.parse("true");    // => true
strbool.parse("yes");     // => true
strbool.parse("off");     // => false
strbool.parse("anything else"); // throws ZodError (invalid_value)

// customizing accepted values
z.stringbool({
  truthy: ["true", "1", "yes", "on", "y", "enabled"],
  falsy: ["false", "0", "no", "off", "n", "disabled"],
});
  • What it demonstrates: the default word lists and how to override them.

Anti-patterns

  • Confusing z.stringbool() with z.coerce.boolean(): z.coerce.boolean() uses raw JS truthiness (any non-empty string is true, including "false"); z.stringbool() actually checks the string against a truthy/falsy word list, so "false" correctly maps to false.

Key Takeaways

  1. For environment variables and form fields, z.stringbool() is almost always the right choice over z.coerce.boolean() — it handles the "false" case correctly.
  2. Matching is case-insensitive by default; opt into { case: "sensitive" } only when that's a real requirement.
  3. The truthy/falsy word lists are fully customizable if the defaults don't match your input source's conventions.

Connects To

  • Primitives & Coercion: contrast with z.coerce.boolean()'s naive truthy/falsy behavior.
  • Booleans: the strict, non-coercing boolean schema.