Skip to content

Support union types for zod generator #237

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

Merged
merged 5 commits into from
Nov 23, 2022

Conversation

alisabzevari
Copy link
Contributor

Fixes #236
Fixes #181

This PR adds support for union types for generating zod schemas when withObjectType is enabled.

@Code-Hex
Copy link
Owner

@alisabzevari Thanks!
Could you add code also yup and myzod?

@alisabzevari
Copy link
Contributor Author

Sure, will do.

Co-authored-by: alexandruluca <[email protected]>
@alisabzevari
Copy link
Contributor Author

I have added support for myzod but apparently yup does not support unions.

@Code-Hex
Copy link
Owner

Code-Hex commented Nov 18, 2022

@alisabzevari I believe you can use mixed and oneof for yup

@alisabzevari
Copy link
Contributor Author

I believe you can use mixed and oneof for yup

I tried that but the generated schema cannot properly validate the object.

@Code-Hex
Copy link
Owner

Code-Hex commented Nov 21, 2022

@alisabzevari Could you add this code for yup in initialEmit: prop ?

function union<T>(...schemas: ReadonlyArray<yup.SchemaOf<T>>): yup.BaseSchema<T> {
  return yup.mixed().test({
    test: (value) => schemas.some((schema) => schema.isValidSync(value))
  })
}

And fix yup generator to generate code like below

function ShapeSchema(): yup.BaseSchema<Shape> {
  return union<Shape>(SquareSchema(), CircleSchema())
}

@alisabzevari
Copy link
Contributor Author

I have added the code you mentioned. Please have a look.

@Code-Hex
Copy link
Owner

@alisabzevari Could you please fix the test?

Copy link
Owner

@Code-Hex Code-Hex left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@Code-Hex Code-Hex merged commit efe8628 into Code-Hex:main Nov 23, 2022
Code-Hex added a commit that referenced this pull request Nov 23, 2022
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

Successfully merging this pull request may close these issues.

zod schema generator does not recognize union types withObjectType option don't support union type
2 participants