davidmdm / myzod

MIT License
315 stars 20 forks source link

Suggestion: `required` operator #39

Closed zhaoyao91 closed 3 years ago

zhaoyao91 commented 3 years ago

if a field is already optional, we have no way to make it required, which prevent us from reusing other schemas.

davidmdm commented 3 years ago

I have added a required method for optional and nullable schemas. It was released just now in version 1.7.0

Let me know if this solves your issue.

Thanks.

zhaoyao91 commented 3 years ago

I see both optional and nullable use require as revert. What happens when I call require on an optional and nullable schema?

davidmdm commented 3 years ago

Well if it was optional and nullable, you would have to call required twice, I figured because it is static you it’s not too confusing and it gives the power of removing either wrapper without removing both.

I was considering adding a more generic helper function that would unwrap a schema recursively but didn’t add that on a first draft. Is that more what you had in mind?

davidmdm commented 3 years ago

Ok I added mzyod.required() in v1.7.1

It calls required on the schema until the top level schema no longer has an optional or nullable schema wrapper.

const optionalSchema = z.string().optional().nullable();

const schema = z.required(optionalSchema) // Simpy a StringType schema.
zhaoyao91 commented 3 years ago

Oops, it's very helpful! Thanks very much.