Coerce values of certain types while allowing values of other types #3797
allen-liaoo
started this conversation in
General
Replies: 1 comment 1 reply
-
You can write your own const schema = z.object({
field: z
.string()
.or(z.number())
.nullable()
.transform((data, ctx) => {
if (data === null || typeof data === "number") return data;
const asNumber = Number(data);
if (isNaN(asNumber)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `The value for "data" is not valid.`,
});
return z.NEVER;
}
return asNumber;
}),
});
type schemaInput = z.input<typeof schema>; // { field: string | number | null }
type schemaOutput = z.output<typeof schema>; // { field: number | null } |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I'm new to zod. I want to be able to coerce
string
tonumber
, but I want to allow the value that isnull
to remainnull
. I'm not sure how to specifically allownull
to pass through uncoerced because coerce would raise an error.Without handling
null
values:Option 1:
Option 1 doesn't work because Number constructor will be called with either
null
, which is not what I intended. I wantnull
to remainnull
.Option 2:
Option 2 doesn't work because if
null
is encountered,z.coerce.number()
raises an error.Any help would be appreciated!
Beta Was this translation helpful? Give feedback.
All reactions