Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing RawCreateParams to z.tuple() doesn't apply to all errors generated by z.tuple(). #3474

Open
DanielBaulig opened this issue May 8, 2024 · 3 comments

Comments

@DanielBaulig
Copy link

DanielBaulig commented May 8, 2024

Example:

const schema = z.tuple([z.string(), z.number()], { message: 'this doesnt look right' });
schema.parse([]); 

This will throw with a ZodIssue of { too_short, 'Array must contain at least 2 elements' } instead of the supplied message.

@DanielBaulig
Copy link
Author

DanielBaulig commented May 8, 2024

Maybe I am misunderstanding what the purpose of the message argument in RawCreateParams is, but if I read this correctly then message seems to only be used under a few very specific circumstances. Is this intended?

@DanielBaulig
Copy link
Author

DanielBaulig commented May 8, 2024

So I just read the pull request and issue that relatively recently added message.

Maybe I'm still lacking some insights here but I kinda agree that adding the message and other shorthands may have been a mistake in terms of ergonomics and clarity. But since it's there it should definitely apply to all errors, not just the two preexisting shorthands plus the invalid_enum_value. That just does not make any sense and the very general name of message provides no inidication, that that is the behavior one should expect.

@DanielBaulig
Copy link
Author

Here's a little code snippet that achieves the desired effect nicely without any changes in zod itself.

const zMapAll = (message: string) => {
  return { errorMap: () => ({ message }) };
}
const schema = z.tuple([z.string(), z.number()], zMapAll('this doesnt look right'));
schema.parse([]); 

I think the main problem for most people is ergonomics of defining an error map combined with the overall complexity of the example in the error map documentation.

I understand that the intention in the documentation is to demonstrate the power of the zod error mappng API, but most people are probably just looking for an easy way to drop in a different error message for any given validator. Maybe adding a simple example to the documentation could be a great way to help with that while reducing confusion and bad API changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant