@conform-to/zod
Version:
Conform helpers for integrating with Zod
81 lines (80 loc) • 2.58 kB
TypeScript
import type { ZodTypeAny } from 'zod';
/**
* @deprecated Conform strip empty string to undefined by default
*/
export declare function ifNonEmptyString(fn: (text: string) => unknown): (value: unknown) => unknown;
export type DefaultCoercionType = 'string' | 'file' | 'number' | 'boolean' | 'date' | 'bigint';
export type CoercionFunction = (value: unknown) => unknown;
/**
* Reconstruct the provided schema with additional preprocessing steps
* This strips empty values to undefined and coerces string to the correct type
*/
export declare function enableTypeCoercion<Schema extends ZodTypeAny>(type: Schema, options: {
cache: Map<ZodTypeAny, ZodTypeAny>;
coerce: (type: ZodTypeAny) => CoercionFunction | null;
stripEmptyValue: CoercionFunction;
}): ZodTypeAny;
/**
* A helper that enhance the zod schema to strip empty value and coerce form value to the expected type with option to customize type coercion.
* @example
*
* ```tsx
* import { parseWithZod, unstable_coerceFormValue as coerceFormValue } from '@conform-to/zod';
* import { z } from 'zod';
*
* // Coerce the form value with default behaviour
* const schema = coerceFormValue(
* z.object({
* // ...
* })
* );
*
* // Coerce the form value with default coercion overrided
* const schema = coerceFormValue(
* z.object({
* ref: z.number()
* date: z.date(),
* amount: z.number(),
* confirm: z.boolean(),
* }),
* {
* // Trim the value for all string-based fields
* // e.g. `z.string()`, `z.number()` or `z.boolean()`
* string: (value) => {
* if (typeof value !== 'string') {
* return value;
* }
*
* const result = value.trim();
*
* // Treat it as `undefined` if the value is empty
* if (result === '') {
* return undefined;
* }
*
* return result;
* },
*
* // Override the default coercion with `z.number()`
* number: (value) => {
* // Pass the value as is if it's not a string
* if (typeof value !== 'string') {
* return value;
* }
*
* // Trim and remove commas before casting it to number
* return Number(value.trim().replace(/,/g, ''));
* },
*
* // Disable coercion for `z.boolean()`
* boolean: false,
* },
* );
* ```
*/
export declare function coerceFormValue<Schema extends ZodTypeAny>(type: Schema, options?: {
defaultCoercion?: {
[key in DefaultCoercionType]?: CoercionFunction | boolean;
};
customize?: (type: ZodTypeAny) => CoercionFunction | null;
}): Schema;