zod icon indicating copy to clipboard operation
zod copied to clipboard

ZodFormattedError does not propagate the custom error format to recursive fields

Open carlgieringer opened this issue 3 years ago • 1 comments

ZodFormattedError accepts two type params.

export type ZodFormattedError<T, U = string>

T is the type of the input schema and U is the type of each error entry. U is important when providing a custom issue mapper. ZodFormattedError uses T to define the shape of the formatted error object, but it does not propagate U to the fields of this object. E.g.:

... ZodFormattedError<NonNullable<T>[K]>

This means that typing fails when trying to access custom error types of a `ZodFormattedError.

Example: the following code should pass typechecking sandbox:

import { z } from "zod";

const Thing = z.object({
  name: z.string().min(2)
});

const result = Thing.safeParse({ name: "a" });
if (!result.success) {
  const formatted = result.error.format((issue) => ({
    code: issue.code,
    message: issue.message
  }));
  console.log(formatted.name?._errors?.code);
}

But instead it fails with `Property 'code' does not exist on type 'string[]'.ts(2339)'

carlgieringer avatar Nov 30 '22 06:11 carlgieringer

Hi, this issue has a simple fix, as presented in #1617.

carlgieringer avatar Dec 08 '22 00:12 carlgieringer

@colinhacks Hi, should I do anything in particular to have the PR for this issue reviewed? Thanks!

carlgieringer avatar Dec 27 '22 21:12 carlgieringer

sometimes you just need to be a squeaky wheel. :D

I approved and merged it

JacobWeisenburger avatar Jan 03 '23 18:01 JacobWeisenburger

I wasn't sure how squeaky I should be. Thanks, @JacobWeisenburger!

carlgieringer avatar Jan 10 '23 04:01 carlgieringer

@carlgieringer Unfortunately this has been reverted in 3.21 for causing infinite recursion & compiler slowdowns. It's possible this can be re-implemented in a way that avoids these issues (maybe) but I had to put out a fix asap and didn't have time to look into it.

colinhacks avatar Mar 04 '23 22:03 colinhacks

@colinhacks too bad! I see the PR that removed the feature and the references to slowness. If I re-attempt, I'll check those.

Also could someone re-open this issue? Or should I just create a new one?

carlgieringer avatar May 26 '23 05:05 carlgieringer

I know this is an old issue / thread, but if anyone has time, could they explain what the actual "recursive type" issue was? As mentioned, since it is just a "6 character change," it is hard to understand how that was able to have such a large performance impact

romellem avatar Apr 18 '24 14:04 romellem