Skip to content

.superRefine is missing "when" parameter #5739

Description

@vilvai

.refine() has a when parameter that allows running a refinement even when the base schema validation fails: #4838

However, .superRefine is missing this parameter.

Example

    const baseSchema = z.object({
      foo: z.number(),
      bar: z.number(),
    });

    const schema = baseSchema.superRefine(
      (data, ctx) => {
        if (data.foo > 10) {
          ctx.addIssue({
            code: "custom",
            message: "foo must be less than 10",
          });
        }
      },
      {
        when: ({ value }) =>
          baseSchema.pick({ foo: true }).safeParse(value).success,
      },
    );

    const result = schema.safeParse({
      foo: 11,
    });

// 

In the above example, result.error.issues will only contain one error: "Invalid input: expected number, received undefined" and not the error from .superRefine

The above example could be replaced with .refine since it only adds one issue, but for more complex use cases where .superRefine is needed, having .when would be useful.

This is a widely requested feature, see for example:
#479 (comment)

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