Skip to content

zod.preprocess v3.22.2 issues are ignored in case of another error in the model #2677

@azhiv

Description

@azhiv

Another issue we found in v3.22.2 is that the schema inside preprocess either isn't executed or doesn't add issues to the context in case the model being parsed contains an error in another field (nonNullableObject below):

import * as zod from 'zod';

const wrapToArray = <T extends zod.ZodTypeAny>(elementSchema: T) =>
  zod.preprocess((val) => [val], zod.array(elementSchema));

const singleItemSchema = zod.object({
  quantity: zod.number(),
});

const itemsStepSchema = zod.object({
  nonNullableObject: zod.object({}),
  items: wrapToArray(singleItemSchema), // swapping this line with the one below results in correct behaviour (2 issues instead of 1)
  // items: singleItemSchema,       
});

const res = itemsStepSchema.safeParse({
  nonNullableObject: null,
  items: {},
});

//@ts-ignore
console.log(res.error.issues.length);  // 3.21 shows 2 errors, 3.22 - only 1
console.log(res);

An error in nonNullableObject hides the preprocess errors. Also, if I remove the preprocess call completely the behaviour becomes correct. This doesn't look right as preprocess stops errors from being populated.
3.21.4:
Screenshot 2023-08-21 at 19 06 17

3.22.2:
Screenshot 2023-08-21 at 19 05 12

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions