From d7d49e77ccd758ee874f7866862840f88f75cbb6 Mon Sep 17 00:00:00 2001 From: Colin McDonnell Date: Mon, 12 Dec 2022 12:18:09 -0800 Subject: [PATCH] Clarify boolean coercion --- README.md | 15 +++++++++++++++ deno/lib/README.md | 15 +++++++++++++++ playground.ts | 12 ++++++++---- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5e6436704..248b5cc60 100644 --- a/README.md +++ b/README.md @@ -591,6 +591,21 @@ z.coerce.bigint(); // BigInt(input) z.coerce.date(); // new Date(input) ``` +**Boolean coercion** + +Zod's boolean coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`. + +```ts +z.coerce.boolean().parse("tuna"); // => true +z.coerce.boolean().parse("true"); // => true +z.coerce.boolean().parse("false"); // => true +z.coerce.boolean().parse(1); // => true +z.coerce.boolean().parse([]); // => true + +z.coerce.boolean().parse(0); // => false +z.coerce.boolean().parse(undefined); // => false +z.coerce.boolean().parse(null); // => false + ### Datetime validation The `z.string().datetime()` method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision. diff --git a/deno/lib/README.md b/deno/lib/README.md index 5e6436704..248b5cc60 100644 --- a/deno/lib/README.md +++ b/deno/lib/README.md @@ -591,6 +591,21 @@ z.coerce.bigint(); // BigInt(input) z.coerce.date(); // new Date(input) ``` +**Boolean coercion** + +Zod's boolean coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`. + +```ts +z.coerce.boolean().parse("tuna"); // => true +z.coerce.boolean().parse("true"); // => true +z.coerce.boolean().parse("false"); // => true +z.coerce.boolean().parse(1); // => true +z.coerce.boolean().parse([]); // => true + +z.coerce.boolean().parse(0); // => false +z.coerce.boolean().parse(undefined); // => false +z.coerce.boolean().parse(null); // => false + ### Datetime validation The `z.string().datetime()` method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision. diff --git a/playground.ts b/playground.ts index 77cb8e37e..1dc3989e6 100644 --- a/playground.ts +++ b/playground.ts @@ -1,7 +1,11 @@ import { z } from "./src"; -const schema = z.object({ - birth_date: z.date().optional(), -}); +console.log(z.coerce.boolean().parse("tuna")); // => true +console.log(z.coerce.boolean().parse("true")); // => true +console.log(z.coerce.boolean().parse("false")); // => true +console.log(z.coerce.boolean().parse(1)); // => true +console.log(z.coerce.boolean().parse([])); // => true -schema.parse({}); +console.log(z.coerce.boolean().parse(0)); // => false +console.log(z.coerce.boolean().parse(undefined)); // => false +console.log(z.coerce.boolean().parse(null)); // => false