Allow to extend field with coerce #5540
GitonioDev
started this conversation in
Ideas
Replies: 1 comment
|
This is a real pain point. Zod's coercion is built into the schema constructor ( Here's a practical workaround using const ApiSchema = z.object({
age: z.number(),
score: z.number(),
active: z.boolean(),
});
// Form version: accepts strings, coerces to the right types
const FormSchema = z.object({
age: z.string().pipe(z.coerce.number()),
score: z.string().pipe(z.coerce.number()),
active: z.string().pipe(z.coerce.boolean()),
});If you want something more automated, you can write a helper that takes an existing schema and produces a coerced version: function coerceShape<T extends z.ZodRawShape>(shape: T) {
const coerced: Record<string, z.ZodTypeAny> = {};
for (const [key, field] of Object.entries(shape)) {
if (field instanceof z.ZodNumber) {
coerced[key] = z.coerce.number();
} else if (field instanceof z.ZodBoolean) {
coerced[key] = z.coerce.boolean();
} else if (field instanceof z.ZodDate) {
coerced[key] = z.coerce.date();
} else if (field instanceof z.ZodBigInt) {
coerced[key] = z.coerce.bigint();
} else if (field instanceof z.ZodString) {
coerced[key] = z.coerce.string();
} else {
coerced[key] = field; // keep as-is
}
}
return z.object(coerced as any);
}
// Usage
const ApiSchema = z.object({
age: z.number(),
score: z.number().min(0).max(100),
active: z.boolean(),
});
const FormSchema = coerceShape(ApiSchema.shape);
// FormSchema accepts string inputs and coerces themThe downside is that this strips refinements ( const FormSchema = z.object({
age: z.coerce.number(),
score: z.coerce.number().pipe(ApiSchema.shape.score), // coerce then validate
active: z.coerce.boolean(),
});The It'd definitely be nice if Zod supported something like |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Let's say you have a schema like
age: z.number()
To have coerce here you must redefine it
age: z.coerce.number()
My idea to have some kind of way to extend that field with coerce
age: shape.age.coerce()
Why? There are multiple reasons one is
All reactions