Skip to main content
Module

x/zod_utilz/mod.ts>zu.coerce

Framework agnostic utilities for Zod
Go to Latest
function zu.coerce
import { zu } from "https://deno.land/x/zod_utilz@0.4.0/mod.ts";
const { coerce } = zu;

Treats coercion errors like normal zod errors. Prevents throwing errors when using safeParse.

Examples

import { zu } from 'zod_utilz' const bigintSchema = zu.coerce( z.bigint() ) bigintSchema.parse( '42' ) // 42n bigintSchema.parse( '42n' ) // 42n zu.SPR( bigintSchema.safeParse( 'foo' ) ).error?.issues[ 0 ].message // 'Expected bigint, received string'

import { zu } from 'zod_utilz' const booleanSchema = zu.coerce( z.boolean() )

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean // only exception to normal boolean coercion rules booleanSchema.parse( 'false' ) // false

// https://developer.mozilla.org/en-US/docs/Glossary/Falsy // falsy => false booleanSchema.parse( false ) // false booleanSchema.parse( 0 ) // false booleanSchema.parse( -0 ) // false booleanSchema.parse( 0n ) // false booleanSchema.parse( '' ) // false booleanSchema.parse( null ) // false booleanSchema.parse( undefined ) // false booleanSchema.parse( NaN ) // false

// truthy => true booleanSchema.parse( 'foo' ) // true booleanSchema.parse( 42 ) // true booleanSchema.parse( [] ) // true booleanSchema.parse( {} ) // true

import { zu } from 'zod_utilz' const numberArraySchema = zu.coerce( z.number().array() )

// if the value is not an array, it is coerced to an array with one coerced item numberArraySchema.parse( 42 ) // [ 42 ] numberArraySchema.parse( '42' ) // [ 42 ]

// if the value is an array, it coerces each item in the array numberArraySchema.parse( [] ) // [] numberArraySchema.parse( [ '42', 42 ] ) // [ 42, 42 ]

zu.SPR( numberArraySchema.safeParse( 'foo' ) ).error?.issues[ 0 ].message // 'Expected number, received nan'

Type Parameters

Schema extends AllowedZodTypes