Skip to content

Add an analogous method to .required() for .nullish() (Feature request) #5348

@aantia

Description

@aantia

Feature Request

Add a method that will strip .nullish() off all properties, similar to how .required() strips .optional() off all properties.

Use Case

In my Zod schemas I have to use .nullish() extensively - essentially we have to support a null value for anything that might also be undefined or simply not present.

This works very well for us, but there is one particular part of the code where we need stricter validation of a particular object. If we were using .optional() we could simply add .required() onto the schema, but as we instead want to strip off .nullish() we do a much less pleasant:

const DerivedSchema = z.strictObject({
  ...BaseSchema.shape,
  propertyName: BaseSchema.shape.propertyName.unwrap().unwrap(),
// etc
}).required();

It would obviously be much nicer-looking if we just did a new schema, but to keep the logic clear and to keep it DRY we prefer to extend the original one.

Something like this would be ideal:

const DerivedSchema = z.strictObject({
  ...BaseSchema.shape
}).notNullish();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions