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

Sum type / oneOfType #321

Closed
rivertam opened this issue Sep 25, 2018 · 6 comments
Closed

Sum type / oneOfType #321

rivertam opened this issue Sep 25, 2018 · 6 comments

Comments

@rivertam
Copy link

Hi there. Sorry if this is already included, but I can't find any documentation or issues regarding it.

I'm looking for a way to validate that a given type is one of multiple possible types. In FP, it would look like number | string, for example. React PropTypes offers this as oneOfType. I think yup would probably have either oneOfType or .or as in .string().or(yup.number()).

Is anything like this supported?

@rivertam
Copy link
Author

It looks like Joi has this as .alternatives as in Joi.alternatives().try([Joi.number(), Joi.string()]).

@jquense
Copy link
Owner

jquense commented Sep 25, 2018

we don't have anything like alternatives due to a few ways in which yup is different than joi. However you can definitely use lazy to dynamically return a new schema type based on a value or other context

@sublimeye
Copy link

@jquense Could you please provide a basic example?

@jquense
Copy link
Owner

jquense commented Oct 8, 2018

something like?

const schema = yup.lazy(value => typeof value === 'number' yup.number() : yup.string())

@Aaronius
Copy link

Aaronius commented Oct 1, 2019

Using lazy is not ideal, because you have to write logic to check the value type before determining which validator to use. :/

@colinhacks
Copy link

@rivertam @Aaronius @sublimeye I hit against this issue as well (among others) so I made a validation library that supports it: https://github.com/vriad/zod

Specifically, there is a built-in "union" type, like so:

const numOrString = z.union([ z.string(), z.number() ])

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

5 participants