Skip to content

[Zod] Default and Optional Interaction #3751

@JamesMcNee

Description

@JamesMcNee

Description

There is a strange interaction in Zod (that I think is a bug and will raise with Zod too) when you have a default value for an optional field. If you chain the .default(<value>) after the .optional() then the optionality of the field is removed completely.

In order to help mitigate this, it would be good to ensure that .optional() is appended at the end of the chain (or at least after .default()).

Reproducible example or configuration

Input schema

{
  "type": "object",
  "properties": {
    "age": {
      "description": "The age of the thing",
      "default": 90,
      "type": "number"
    }
  },
  "required": []
}

Produces output Zod:

const schema = z.object({
  age: z.number().register(z.globalRegistry, {
    description: 'The age of the thing'
  }).optional().default(90)
})

Which will fail the following, due to incorrectly being a required property

type SchemaType = z.infer<typeof schema>
const foo: SchemaType = {} // Should allow the empty here, will error due to lack of `age` property

OpenAPI specification (optional)

No response

System information (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug 🔥Broken or incorrect behavior.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions