Skip to content

Conversation

@sentik
Copy link
Contributor

@sentik sentik commented Oct 28, 2025

Fix: Handle falsy default values in Zod schema generation

Problem

When a schema has default: false (or other falsy values like 0, '', or null), the generated Zod schema incorrectly omits the .default() method and uses .optional() instead. This occurs because the condition if (!required && schema.default) treats falsy values as falsy in JavaScript.

Example from issue #2222:

schema:
  type: object
  properties:
    primary:
      type: boolean
      default: false

Before:

export const patchV2OrganisationsOrganisationIdSchemesSchemeIdPrimaryBody = zod.object({
  "primary": zod.boolean().optional()  // ❌ Missing default
})

Expected:

export const patchV2OrganisationsOrganisationIdSchemesSchemeIdPrimaryBody = zod.object({
  "primary": zod.boolean().default(patchV2OrganisationsOrganisationIdSchemesSchemeIdPrimaryBodyPrimaryDefault)
})

Solution

Changed the condition from schema.default to schema.default !== undefined to properly detect when a default value is set, regardless of whether it's a falsy value.

// Changed from:
if (!required && schema.default) {

// To:
if (!required && schema.default !== undefined) {

This ensures that all default values, including falsy ones, are properly applied to the Zod schema.

Fixed a bug where falsy default values (false, 0, '', null) were not properly
applied to generated Zod schemas. The condition used `schema.default` which
falsely treats falsy values as undefined.

Changed the check to `schema.default !== undefined` to properly detect when
a default value is set, regardless of its truthiness.

Added test coverage for:
- default: true
- default: false
- no default (undefined)

Fixes orval-labs#2222
@melloware melloware added the zod Zod related issue label Oct 28, 2025
@melloware melloware linked an issue Oct 28, 2025 that may be closed by this pull request
@melloware melloware merged commit db91abd into orval-labs:master Oct 28, 2025
0 of 2 checks passed
zhu-hong pushed a commit to zhu-hong/orval that referenced this pull request Oct 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

zod Zod related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Zod: Default falsy value of boolean is never evaluated

2 participants