javascript JSON.stringify converts zodjs boolean to a number (1 or 0)

Viewed 414


I am building an app with Typescript/nextjs/reactjs and I am using zodjs schema and types to validate user input in my frontend and backend. One of my problem is that when I JSON.stringify my user input (an object with a zod boolean) to send it to my backend/api, the boolean will be changed in 1 for true and 0 for false. That ends in an validation error in my backend.

The validation error looks like this:

<br/>
"code": "invalid_type",<br/>
"expected": "boolean",<br/>
"received": "number",<br/>
...<br/>
"message": "Expected boolean, received number"<br/>

My Zodjs Object/Schema and type looks like this:

export const SomeObject = z
  .object({
  ...
  active: z.boolean().default(true),
  ...
 }).strict();
export type SomeObject = z.infer<typeof SomeObject>;

what am I doing wrong?

1 Answers

I think you are looking for something like Refine and/or Transform

Maybe something like:

export const SomeObject = z
  .object({
  ...
  active: z.enum(['0', '1']).transform(val => val === '1').default('1'),
  ...
 }).strict();
Related