2.7 KiB
Coerce Utilities
Purpose
The coerce utilities allow schemas to accept a broader range of input types by converting them before validation. They bridge the gap between raw HTTP parameters (always strings), form data, and strongly-typed schema expectations. Each coerce function is pure and never throws — failures return null. The higher-order coerce(schema) wrapper applies the appropriate coercion strategy for string inputs and falls back to the raw schema if no coercion path works.
Features
coerceString(input)— always succeeds viaString(input)coerceNumber(input)— viaNumber(input), returnsnullfor NaNcoerceBoolean(input)— handles"true"/"false"/"1"/"0"/1/0/true/falsecoerceDate(input)— converts ISO strings and timestamps toDatecoerce(schema)— wraps any schema with automatic string coercion
Usage: Basic Example
import { coerce, number } from "@suaveplan/validation";
const ageSchema = coerce(number().int().min(0));
ageSchema.parse("25"); // 25 (string coerced to number)
ageSchema.parse(25); // 25 (passthrough)
Usage: Advanced Example
import { coerce, boolean, date, object } from "@suaveplan/validation";
// Query parameter parsing (all values arrive as strings)
const QueryParams = object({
active: coerce(boolean()),
since: coerce(date()),
limit: coerce(number().int().max(100)),
});
QueryParams.parse({
active: "true",
since: "2024-01-01",
limit: "50",
});
API Reference
coerceString(input: unknown): string
Calls String(input). Always succeeds; never returns null.
coerceNumber(input: unknown): number | null
Calls Number(input). Returns null if the result is NaN.
coerceBoolean(input: unknown): boolean | null
Recognises true/false (booleans passthrough), "true"/"1"/1 → true, "false"/"0"/0 → false. Returns null for unrecognised input.
coerceDate(input: unknown): Date | null
Passes through existing Date instances. Converts strings and numbers via new Date(input). Returns null if the result is an invalid date.
coerce<T>(schema: BaseSchema<unknown, T>): CoercedSchema<T>
Returns a CoerceWrapperSchema that attempts string coercions in order (number → boolean → date) for string inputs, falling back to the raw schema if none succeed.
type CoercedSchema<T>
Alias for BaseSchema<unknown, T>.
Implementation Notes
coerce(schema)clearsctx.issuesbetween coercion attempts so that intermediate failures don't pollute the final error list.- Coercion order for string inputs is: numeric → boolean → date → raw. The first successful conversion is used.
- For non-string inputs,
coerce(schema)delegates directly to the inner schema with no transformation.