Skip to content

Commit

Permalink
Clarify boolean coercion
Browse files Browse the repository at this point in the history
  • Loading branch information
Colin McDonnell committed Dec 12, 2022
1 parent 1161b8f commit d7d49e7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
15 changes: 15 additions & 0 deletions README.md
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions deno/lib/README.md
Expand Up @@ -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.
Expand Down
12 changes: 8 additions & 4 deletions 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

0 comments on commit d7d49e7

Please sign in to comment.