zod
zod copied to clipboard
Impossible to provide custom issue code
In your documentation said
This is the error code throw by refinements (unless you are using
superRefinein which case it's possible to throw issues of anycode)
But when i provide custom code TS complains
TS2322: Type '"duplicated_id"' is not assignable to type '"invalid_enum_value" | "invalid_type" | "unrecognized_keys" | "invalid_literal" | "invalid_union" | "invalid_union_discriminator" | "invalid_arguments" | "invalid_return_type" | ... 6 more ... | "too_small"'.```
Yeah the code still needs to be defined in ZodIssueCode. This is necessary for the discriminated union to work properly (ZodIssue is a big discriminated union of every issue type) as well as Zod's whole error message generation system. I'll think about ways to make this more extensible but I recommend sticking with "custom" for now.
@dilame, was that a satisfactory answer? Or do you have any other questions? If not, I'd like to close this issue.
The answer is ok, but it is not a question but issue, and it still persists – in docs you have written in two places that user can provide custom error code, but actually you can not. I think in order to resolve this issue we need either fix docs or code.
I'll take a look at the docs. Would you be able to give me links to where the docs say this?
You can use global search to find this text in the main docs page here
Normally refinements always create issues with a ZodIssueCode.custom error code, but with superRefine you can create any issue of any code.
And here (ZodIssueCode.custom description)
unless you are using superRefine in which case it's possible to throw issues of any code
And, by the way, my vote is for fixing the code instead of docs because actually i use this feature with // @ts-ignore flag.
I'm not opposed to changing the code. I just want to make sure the docs are reflecting the latest release.
As far as changing the code, that's something you will need to convince @colinhacks. I'll leave this issue open for you to do that if you want.
I updated the docs here: https://github.com/colinhacks/zod/commit/1115bd143744aa903ae9426ac3c116790dc14154
As a workaround for no user-defined error codes, I am using .refine() with params: https://codesandbox.io/s/blue-platform-xmbq2u?file=/src/index.ts
Seems to be a very simple solution to what must be a very common use-case, but it wasn't immediately clear from the docs that we can make params anything we want.
If I am not doing something inadvisable in the demo - and if zod won't support custom error codes in the near future - perhaps an example like this could be added to the docs.