Skip to content

fix(zod): preserve null type when .nullish() is applied to named schema reference#145

Open
daniel-rose wants to merge 3 commits intotazo90:mainfrom
daniel-rose:fix/zod-nullish-allof-ref
Open

fix(zod): preserve null type when .nullish() is applied to named schema reference#145
daniel-rose wants to merge 3 commits intotazo90:mainfrom
daniel-rose:fix/zod-nullish-allof-ref

Conversation

@daniel-rose
Copy link
Copy Markdown
Contributor

@daniel-rose daniel-rose commented May 5, 2026

Description

When applying .nullish() or .nullable() to a field that references a named schema (producing a $ref), the generator wrapped the reference in allOf: [{ $ref }] but silently dropped the null type. The field was not nullable in the generated spec.

The fix transforms the output to anyOf: [{ $ref }, { type: 'null' }], which is the correct OpenAPI 3.1 representation. The existing version processor handles 3.0 downgrade automatically (and is now also fixed to preserve outer schema metadata like description during that downgrade).

Closes #142

Type of Change

  • 🐛 fix: Bug fix

Changes

  • packages/openapi-core/src/schema/zod/zod-converter.ts: Two locations fixed:
    1. Direct SchemaIdentifier.nullable() / SchemaIdentifier.nullish() path (line ~1072): now produces anyOf: [{ $ref }, { type: 'null' }] instead of bare allOf: [{ $ref }]
    2. processZodChain nullable/nullish case (line ~1770): when schema.allOf is set, transforms to anyOf with null branch instead of silently skipping
  • packages/openapi-core/src/openapi/version-processor.ts: downgradeSchemaForOpenApi30 now preserves outer metadata (e.g. description) when collapsing anyOf: [{ $ref }, { type: 'null' }] to { $ref, nullable: true }
  • tests/integration/regressions/zod-nullability.test.ts: Two regression tests added for .nullish() and .nullable() on named schema references

Checklist

  • pnpm check passes
  • Tested locally (pnpm test:unit, pnpm test:integration and pnpm build)
  • Documentation updated (if needed)

…ma reference

When a field references a named Zod schema and .nullable() or .nullish() is
called, the generator was wrapping the $ref in allOf but silently dropping the
null type. The fix transforms the output to anyOf: [{ $ref }, { type: 'null' }],
the correct OpenAPI 3.1 representation. The version processor is also fixed to
carry outer schema metadata (e.g. description) when downgrading anyOf to
nullable: true for OpenAPI 3.0.

Closes tazo90#142
@daniel-rose daniel-rose force-pushed the fix/zod-nullish-allof-ref branch from 34b443e to f614b77 Compare May 5, 2026 18:27
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.

bug: .nullish() on named schema field loses null type when allOf is generated

1 participant