Skip to content

fix(zod): add type field to generated enums for openapi compatibility#1478

Open
Sigmabrogz wants to merge 2 commits intomiddleapi:mainfrom
Sigmabrogz:fix/issue-1453-zod-string-literal-openapi
Open

fix(zod): add type field to generated enums for openapi compatibility#1478
Sigmabrogz wants to merge 2 commits intomiddleapi:mainfrom
Sigmabrogz:fix/issue-1453-zod-string-literal-openapi

Conversation

@Sigmabrogz
Copy link

@Sigmabrogz Sigmabrogz commented Mar 16, 2026

Fixes #1453

Currently enums created with ZodEnum do not generate a type field which leads to issues for OpenAPI tooling like hey-api that expects it. Added type: "string" (or inferred type) alongside the enum array to ensure broader compatibility.

Summary by CodeRabbit

  • Improvements

    • JSON Schema generation for enums now includes explicit primitive type information when determinable, producing more precise and standards-compliant schemas.
    • Native/mixed enums are handled to emit appropriate type or omit it for mixed types.
  • Bug Fixes

    • Enum value validation and coercion behavior improved to correctly recognize numeric, string, and mixed enum members.
  • Tests

    • Expanded tests to cover numeric and mixed enums and updated expectations for enum-containing structures.

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 16, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 16, 2026

📝 Walkthrough

Walkthrough

Added logic to derive and emit explicit JSON Schema type for Zod enums and native enums, introduced a shared getValidEnumValues helper, and updated coercion and tests to handle numeric, string, and mixed enums explicitly.

Changes

Cohort / File(s) Summary
Converter core
packages/zod/src/converter.ts, packages/zod/src/zod4/converter.ts
Added getValidEnumValues(obj); ZodEnum now emits { type: 'string', enum: [...] }; ZodNativeEnum emits `{ enum: [...], type?: 'string'
Coercion logic
packages/zod/src/coercer.ts
Added getValidEnumValues and switched native-enum checks/coercion to use filtered enum values (exclude reverse numeric mappings), affecting string→number coercion and membership checks.
Unit tests — converter
packages/zod/src/converter.test.ts, packages/zod/src/zod4/converter.native.test.ts, packages/zod/src/zod4/converter.structure.test.ts
Updated expectations to require explicit type: 'string' for string-backed enums; added tests for NumericEnum (type: 'number') and MixedEnum (no type emitted). Tuple/prefixItems tests updated accordingly.
Unit tests — coercer
packages/zod/src/coercer.test.ts, packages/zod/src/zod4/coercer.native.test.ts
Added NumericEnum and MixedEnum cases and extended nativeEnum coercion tests to cover numeric and mixed enum coercion behavior.
Metadata / packaging
manifest_file, package.json
Minor manifest/package metadata adjustments (lines changed).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

size:M

Poem

🐰 I hopped through enums, both small and wide,
Picked valid values that try to hide.
I tell the schema when strings are true,
Or numbers only — mixed ones stay askew.
Hop, test, convert — the spec smiles anew. 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding a type field to enum generation for OpenAPI compatibility, which aligns with the primary objective to fix the issue where Zod enums lacked explicit type information.
Linked Issues check ✅ Passed The PR fulfills the linked issue #1453 requirement by implementing automatic type field injection for enums, enabling OpenAPI tools to correctly identify string enums without user workarounds.
Out of Scope Changes check ✅ Passed All changes are directly scoped to enum handling across converter and coercer modules, including new helper functions and test coverage; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can use TruffleHog to scan for secrets in your code with verification capabilities.

Add a TruffleHog config file (e.g. trufflehog-config.yml, trufflehog.yml) to your project to customize detectors and scanning behavior. The tool runs only when a config file is present.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves an issue where ZodEnum and ZodNativeEnum schemas, when converted to JSON schema, were missing the crucial 'type' field. This omission led to compatibility problems with various OpenAPI tools, such as hey-api. The changes introduce the 'type' field, setting it to 'string' for standard Zod enums and dynamically inferring 'string' or 'number' for native TypeScript enums, thereby improving the robustness and interoperability of generated schemas.

Highlights

  • OpenAPI Compatibility: Added a 'type' field to generated enum schemas to ensure compatibility with OpenAPI tooling that expects this field.
  • ZodEnum Handling: Modified the ZodToJsonSchemaConverter to explicitly add "type": "string" for ZodEnum instances.
  • ZodNativeEnum Type Inference: Enhanced ZodNativeEnum conversion to infer the 'type' as either 'string' or 'number' based on the enum's values.
  • Test Coverage: Updated existing test cases across multiple converter test files to reflect the new 'type' field in expected enum outputs.
Changelog
  • packages/zod/src/converter.test.ts
    • Updated test cases for z.enum and z.nativeEnum to include the expected type: 'string' property in the generated schema.
  • packages/zod/src/converter.ts
    • Modified the ZodToJsonSchemaConverter to add type: 'string' for ZodEnum conversions.
    • Implemented type inference for ZodNativeEnum conversions, setting type to 'string' or 'number' based on the enum's values.
  • packages/zod/src/zod4/converter.native.test.ts
    • Adjusted test cases for z.enum to assert the presence of type: 'string' in the output schema.
  • packages/zod/src/zod4/converter.structure.test.ts
    • Updated test cases involving z.tuple containing z.enum to expect the type: 'string' property within the enum definition.
  • packages/zod/src/zod4/converter.ts
    • Modified the ZodToJsonSchemaConverter for Zod v4 compatibility to include type: 'string' for enum schema generation.
Activity
  • No specific activity (comments, reviews, etc.) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@dosubot dosubot bot added bug Something isn't working javascript Pull requests that update javascript code labels Mar 16, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request aims to add a type field to generated schemas for Zod enums to improve OpenAPI compatibility. While the intent is good and the changes for string-based enums are correct, the implementation introduces bugs for numeric enums in both the Zod v3 and Zod v4 converters. For Zod v3's ZodNativeEnum, the logic incorrectly handles TypeScript's numeric enum representation. For Zod v4's z.enum, the type is incorrectly hardcoded to string, failing to account for numeric enums. I've added specific comments detailing these issues.

const schema_ = schema as ZodNativeEnum<EnumLike>

return [true, { enum: Object.values(schema_._def.values) }]
return [true, { type: typeof Object.values(schema_._def.values)[0] === 'number' ? 'number' : 'string', enum: Object.values(schema_._def.values) }]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This implementation for ZodNativeEnum has two issues:

  1. Inefficiency: It calls Object.values(schema_._def.values) twice, which can be optimized by storing the result in a variable.
  2. Bug with numeric enums: For a numeric TypeScript enum like enum MyEnum { A }, Object.values(MyEnum) returns ['A', 0]. Your logic will check the type of the first element ('A'), incorrectly infer the type as 'string', and include the string key in the final enum array for the OpenAPI schema. This is incorrect and will generate invalid schemas for numeric enums.

A more robust implementation is needed to correctly handle native numeric enums by filtering out the reverse-mapped keys that TypeScript generates.

case 'enum': {
const enum_ = schema as $ZodEnum
return [true, { enum: Object.values(enum_._zod.def.entries) }]
return [true, { type: 'string', enum: Object.values(enum_._zod.def.entries) }]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Hardcoding the type as 'string' is incorrect for numeric enums, which are supported by z.enum() in Zod v4 (e.g., by passing a numeric native enum). This will generate an invalid OpenAPI schema for such cases.

You should infer the type from the enum values. For example:

const values = Object.values(enum_._zod.def.entries);
const type = values.every(v => typeof v === 'number') ? 'number' : 'string';
return [true, { type, enum: values }];

Since Zod v4's z.enum does not support mixed-type enums, checking if all values are numbers is a safe way to determine the type.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/zod/src/converter.ts`:
- Line 352: Add a converter unit test in converter.test.ts that calls
z.nativeEnum(TestEnum) where TestEnum is mixed (e.g., A = 123, B = 'string') to
reproduce the bug, then change the inference in converter.ts so it doesn't use
typeof on the array itself; instead inspect each entry of schema_._def.values
(e.g., values = Object.values(schema_._def.values)) and determine if all entries
are numbers, all are strings, or mixed, then set the returned type to 'number'
if all numbers, 'string' if all strings, or omit/mark as mixed (or use a neutral
representation) and always return the full values array as the enum; update the
logic around schema_._def.values accordingly to ensure mixed enums produce the
correct enum array and no incorrect single-type tag.

In `@packages/zod/src/zod4/converter.ts`:
- Line 433: The return for z.enum handling currently hardcodes type: 'string'
which breaks JSON Schema for numeric or mixed enums; update the logic around the
branch returning [true, { type: 'string', enum:
Object.values(enum_._zod.def.entries) }] to inspect the enum values
(Object.values(enum_._zod.def.entries)), determine their primitive types (all
'string' -> type: 'string', all 'number' -> type: 'number', all 'boolean' ->
type: 'boolean'), and if the enum is mixed types omit the type property entirely
and only emit the enum array; keep the same return shape but conditionally
include the type field so functions handling z.enum in converter.ts produce
valid JSON Schema.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 92c762e1-845e-4bb7-a349-0957c764426d

📥 Commits

Reviewing files that changed from the base of the PR and between 62c9665 and 2e89be2.

📒 Files selected for processing (5)
  • packages/zod/src/converter.test.ts
  • packages/zod/src/converter.ts
  • packages/zod/src/zod4/converter.native.test.ts
  • packages/zod/src/zod4/converter.structure.test.ts
  • packages/zod/src/zod4/converter.ts

const schema_ = schema as ZodNativeEnum<EnumLike>

return [true, { enum: Object.values(schema_._def.values) }]
return [true, { type: typeof Object.values(schema_._def.values)[0] === 'number' ? 'number' : 'string', enum: Object.values(schema_._def.values) }]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Find numeric/mixed TS enums (possible converter inputs):"
rg -nP --type=ts 'enum\s+[A-Za-z_]\w*\s*\{[\s\S]*?=\s*\d' -g '!**/*.d.ts'

echo
echo "2) Find z.nativeEnum / z.enum callsites using enum identifiers:"
rg -nP --type=ts '\bz\.(nativeEnum|enum)\s*\(\s*[A-Z][A-Za-z0-9_]*\s*\)'

echo
echo "3) Check converter tests for numeric/mixed enum coverage:"
rg -nP --type=ts 'nativeEnum|enum\(' packages/zod/src/**/*

Repository: middleapi/orpc

Length of output: 117


🏁 Script executed:

# First, check the structure and find the converter.ts file
find . -name "converter.ts" -type f

Repository: middleapi/orpc

Length of output: 198


🏁 Script executed:

# Read the converter.ts file around line 352 to see the actual code
wc -l packages/zod/src/converter.ts

Repository: middleapi/orpc

Length of output: 91


🏁 Script executed:

# Get the specific lines around 352
sed -n '345,360p' packages/zod/src/converter.ts

Repository: middleapi/orpc

Length of output: 595


🏁 Script executed:

# Look for ZodNativeEnum case handling in the file
rg -n "ZodNativeEnum" packages/zod/src/converter.ts -A 3 -B 1

Repository: middleapi/orpc

Length of output: 440


🏁 Script executed:

# Check if there are any test files for native enums
find . -name "*test*" -o -name "*spec*" | xargs grep -l "nativeEnum\|ZodNativeEnum" 2>/dev/null || echo "No test files found with nativeEnum"

Repository: middleapi/orpc

Length of output: 212


🏁 Script executed:

# Search for native or enum in the converter test file
grep -n "enum\|native" packages/zod/src/converter.test.ts | head -30

Repository: middleapi/orpc

Length of output: 802


🏁 Script executed:

# Look for any z.enum or z.nativeEnum usage in test file
grep -n "z\.enum\|z\.nativeEnum\|ZodNativeEnum" packages/zod/src/converter.test.ts -A 5 -B 2

Repository: middleapi/orpc

Length of output: 361


🏁 Script executed:

# Check what types of enums are being tested
rg -n "enum.*=" packages/zod/src/converter.test.ts -A 2 -B 1 | head -50

Repository: middleapi/orpc

Length of output: 40


🏁 Script executed:

# Let's also check if there are any actual enum definitions in the test file
sed -n '1,100p' packages/zod/src/converter.test.ts

Repository: middleapi/orpc

Length of output: 2923


🏁 Script executed:

# Get the ExampleEnum definition
sed -n '152,160p' packages/zod/src/converter.test.ts

Repository: middleapi/orpc

Length of output: 210


🏁 Script executed:

# Search for any numeric enum examples in test files
rg -n "enum.*=.*[0-9]" packages/zod/src --type=ts

Repository: middleapi/orpc

Length of output: 40


🏁 Script executed:

# Let's understand TypeScript numeric enum behavior by checking if there are any numeric enums in the codebase
find . -name "*.ts" -type f | xargs grep -n "enum.*=" | grep -E "=\s*[0-9]" | head -20

Repository: middleapi/orpc

Length of output: 908


🏁 Script executed:

# Check the schema object structure to understand what _def.values contains
rg -n "_def\.values" packages/zod/src/converter.ts -B 3 -A 3

Repository: middleapi/orpc

Length of output: 615


🏁 Script executed:

# Search for actual enum definitions in the source code (excluding node_modules)
find packages -name "*.ts" -type f | xargs grep -n "enum.*{" -A 5 | grep -E "(enum|=\s*[0-9])" | head -30

Repository: middleapi/orpc

Length of output: 2581


🏁 Script executed:

# Check zod's type definitions to understand what _def.values contains for nativeEnum
rg -n "nativeEnum" packages/zod/src --type=ts -B 3 -A 3

Repository: middleapi/orpc

Length of output: 2614


🏁 Script executed:

# Verify if there's any runtime behavior we can understand - check how the converter actually handles different enum types
rg -n "Object.values.*_def" packages/zod/src/converter.ts -B 5 -A 5

Repository: middleapi/orpc

Length of output: 516


🏁 Script executed:

# Check if there are any comments or documentation about enum handling
rg -n "enum|Enum" packages/zod/src/converter.ts | head -20

Repository: middleapi/orpc

Length of output: 570


🏁 Script executed:

# Check the TestEnum definition
sed -n '13,30p' packages/zod/src/coercer.test.ts

Repository: middleapi/orpc

Length of output: 325


🏁 Script executed:

# Check if there's a converter test for numeric enums
grep -n "TestEnum\|numeric\|number.*enum" packages/zod/src/converter.test.ts -B 2 -A 2

Repository: middleapi/orpc

Length of output: 40


🏁 Script executed:

# Look for all test cases in converter.test.ts for nativeEnum
grep -n "nativeEnum\|z\.enum" packages/zod/src/converter.test.ts -B 3 -A 3

Repository: middleapi/orpc

Length of output: 344


🏁 Script executed:

# Let's understand what Object.values returns for a numeric enum by creating a test
python3 << 'EOF'
# Simulate TypeScript numeric enum behavior in Python
# In TypeScript: enum E { A = 0 } creates { 0: 'A', A: 0 }
# Object.values would return ['A', 0]

numeric_enum_like = {
    0: 'A',
    'A': 0,
    1: 'B', 
    'B': 1
}

values = list(numeric_enum_like.values())
print("Values:", values)
print("First value:", values[0])
print("Type of first value:", type(values[0]))
print("Is first value number?", isinstance(values[0], (int, float)))
EOF

Repository: middleapi/orpc

Length of output: 161


🏁 Script executed:

# Check if there's coverage for numeric enum in the actual converter tests
sed -n '150,210p' packages/zod/src/converter.test.ts

Repository: middleapi/orpc

Length of output: 1243


🏁 Script executed:

# Check what Zod's nativeEnum actually passes to _def.values
rg -n "nativeEnum.*TestEnum" packages/zod/src -B 2 -A 5

Repository: middleapi/orpc

Length of output: 989


🏁 Script executed:

# Verify the coercer test to understand the mixed enum scenario better
sed -n '13,20p' packages/zod/src/coercer.test.ts

Repository: middleapi/orpc

Length of output: 175


🏁 Script executed:

# Check if there's a separate zod4 converter test and what it covers
ls -la packages/zod/src/zod4/*converter*.ts

Repository: middleapi/orpc

Length of output: 1116


🏁 Script executed:

# Look at zod4 converter test for enum coverage
grep -n "nativeEnum\|ExampleEnum" packages/zod/src/zod4/converter.native.test.ts -B 2 -A 3

Repository: middleapi/orpc

Length of output: 334


🏁 Script executed:

# Critical finding: Let's check if mixed enums are actually used with z.nativeEnum anywhere
rg -n "z\.nativeEnum.*TestEnum" packages/zod/src --type=ts -B 1 -A 1

Repository: middleapi/orpc

Length of output: 574


🏁 Script executed:

# Check what the converter produces for the mixed enum - trace through coercer tests
cat packages/zod/src/coercer.test.ts | grep -A 15 "enum TestEnum"

Repository: middleapi/orpc

Length of output: 297


🏁 Script executed:

# See if there's a missing test case in converter.test.ts for mixed enums
grep -n "TestEnum" packages/zod/src/converter.test.ts

Repository: middleapi/orpc

Length of output: 40


🏁 Script executed:

# Let's understand the actual problem: what does Object.values return for a mixed enum?
node << 'EOF'
// Simulate what Zod receives for a mixed enum
const TestEnum = {
  NUMBER: 123,
  STRING: 'string',
  123: 'NUMBER',    // TS reverse mapping for numeric properties
  string: 'STRING'   // This doesn't exist in actual TS but let's check
};

console.log("Object.values(TestEnum):", Object.values(TestEnum));
console.log("First value:", Object.values(TestEnum)[0]);
console.log("Type of first value:", typeof Object.values(TestEnum)[0]);
console.log("\nWould produce: type:", typeof Object.values(TestEnum)[0] === 'number' ? 'number' : 'string');
console.log("Enum values:", Object.values(TestEnum));
EOF

Repository: middleapi/orpc

Length of output: 248


🏁 Script executed:

# Check if z.nativeEnum is used with mixed enum in converter or if it's only in coercer
rg -n "z\.nativeEnum" packages/zod/src/converter.test.ts -B 2 -A 2

Repository: middleapi/orpc

Length of output: 187


🏁 Script executed:

# Verify the suggested fix logic with TestEnum
node << 'EOF'
// TestEnum from the codebase
const TestEnum = {
  NUMBER: 123,
  STRING: 'string',
  123: 'NUMBER',    // TS reverse mapping
};

// Suggested fix logic
const enumValues = Object.entries(TestEnum)
  .filter(([key]) => Number.isNaN(Number(key)))  // drop TS reverse numeric keys
  .map(([, value]) => value);

console.log("After filter:");
console.log("Enum values:", enumValues);
console.log("Value types:", [...new Set(enumValues.map(v => typeof v))]);

const valueTypes = new Set(enumValues.map(v => typeof v));
console.log("Size of valueTypes set:", valueTypes.size);
console.log("Should add type field?", valueTypes.size === 1);

// Current problematic code
console.log("\nCurrent code would produce:");
const currentType = typeof Object.values(TestEnum)[0] === 'number' ? 'number' : 'string';
console.log("type:", currentType);
console.log("enum:", Object.values(TestEnum));
console.log("Problem: type is 'string' but enum includes", Object.values(TestEnum).filter(v => typeof v === 'number'));
EOF

Repository: middleapi/orpc

Length of output: 321


🏁 Script executed:

# Verify: is there a converter test for z.nativeEnum with mixed enum?
find packages/zod/src -name "*converter*test*" -type f -exec grep -l "nativeEnum.*TestEnum\|TestEnum.*nativeEnum" {} \;

Repository: middleapi/orpc

Length of output: 40


ZodNativeEnum type inference is brittle for mixed enums; missing converter test coverage.

Line 352 uses typeof Object.values(schema_._def.values)[0] to infer type, which produces contradictory schemas for mixed enums (e.g., enum Test { A = 123, B = 'string' }). While coercer.test.ts tests z.nativeEnum(TestEnum) with the mixed enum, converter.test.ts lacks this coverage, exposing the bug: the current code would incorrectly generate type: 'string' with values ['NUMBER', 123, 'string'].

Add a converter test for z.nativeEnum(TestEnum), then fix type inference to handle uniform vs. mixed enums:

Suggested fix
       case ZodFirstPartyTypeKind.ZodNativeEnum: {
         const schema_ = schema as ZodNativeEnum<EnumLike>
-
-        return [true, { type: typeof Object.values(schema_._def.values)[0] === 'number' ? 'number' : 'string', enum: Object.values(schema_._def.values) }]
+        const enumValues = Object.entries(schema_._def.values)
+          .filter(([key]) => Number.isNaN(Number(key))) // drop TS reverse numeric keys
+          .map(([, value]) => value) as Array<string | number>
+
+        const valueTypes = new Set(enumValues.map(v => typeof v))
+        const json: Exclude<JSONSchema, boolean> = { enum: enumValues }
+
+        if (valueTypes.size === 1) {
+          json.type = typeof enumValues[0] === 'number' ? 'number' : 'string'
+        }
+
+        return [true, json]
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return [true, { type: typeof Object.values(schema_._def.values)[0] === 'number' ? 'number' : 'string', enum: Object.values(schema_._def.values) }]
case ZodFirstPartyTypeKind.ZodNativeEnum: {
const schema_ = schema as ZodNativeEnum<EnumLike>
const enumValues = Object.entries(schema_._def.values)
.filter(([key]) => Number.isNaN(Number(key))) // drop TS reverse numeric keys
.map(([, value]) => value) as Array<string | number>
const valueTypes = new Set(enumValues.map(v => typeof v))
const json: Exclude<JSONSchema, boolean> = { enum: enumValues }
if (valueTypes.size === 1) {
json.type = typeof enumValues[0] === 'number' ? 'number' : 'string'
}
return [true, json]
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/zod/src/converter.ts` at line 352, Add a converter unit test in
converter.test.ts that calls z.nativeEnum(TestEnum) where TestEnum is mixed
(e.g., A = 123, B = 'string') to reproduce the bug, then change the inference in
converter.ts so it doesn't use typeof on the array itself; instead inspect each
entry of schema_._def.values (e.g., values = Object.values(schema_._def.values))
and determine if all entries are numbers, all are strings, or mixed, then set
the returned type to 'number' if all numbers, 'string' if all strings, or
omit/mark as mixed (or use a neutral representation) and always return the full
values array as the enum; update the logic around schema_._def.values
accordingly to ensure mixed enums produce the correct enum array and no
incorrect single-type tag.

case 'enum': {
const enum_ = schema as $ZodEnum
return [true, { enum: Object.values(enum_._zod.def.entries) }]
return [true, { type: 'string', enum: Object.values(enum_._zod.def.entries) }]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enum can be number, ... or mix of them so I don't think your approach is acceptable now.

@dosubot dosubot bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Mar 16, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/zod/src/zod4/coercer.native.test.ts (1)

9-17: Unused enum declarations.

NumericEnum and MixedEnum are declared but not used in any test cases in this file. The existing tests only use TestEnum. Either add test cases that exercise these enums or remove the unused declarations.

Option 1: Add test cases for numeric and mixed enums
   {
     name: 'nativeEnum - 123n',
     schema: z.enum(TestEnum),
     input: '123n',
   },
+  {
+    name: 'nativeEnum(NumericEnum) - 1',
+    schema: z.enum(NumericEnum),
+    input: '1',
+    expected: 1,
+  },
+  {
+    name: 'nativeEnum(MixedEnum) - 1',
+    schema: z.enum(MixedEnum),
+    input: '1',
+    expected: 1,
+  },
   {
     name: 'enum - 123',
Option 2: Remove unused declarations
-enum NumericEnum {
-  A = 1,
-  B = 2,
-}
-
-enum MixedEnum {
-  A = 1,
-  B = 'b',
-}
-
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/zod/src/zod4/coercer.native.test.ts` around lines 9 - 17, The file
declares NumericEnum and MixedEnum but never uses them; either remove those
unused enum declarations or add tests that exercise them analogous to the
existing TestEnum cases—specifically add unit tests that import/define
NumericEnum and MixedEnum and assert coercion/validation behavior using the same
test patterns as for TestEnum (copy the structure of the TestEnum test blocks
and substitute NumericEnum and MixedEnum to cover numeric-only and mixed
string/numeric enum coercion scenarios).
packages/zod/src/coercer.ts (1)

31-38: Consider extracting shared helper to avoid duplication.

This getValidEnumValues function is identical to the one in packages/zod/src/converter.ts (lines 77-84). Consider extracting it to a shared utility module to adhere to DRY principles.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/zod/src/coercer.ts` around lines 31 - 38, The getValidEnumValues
helper is duplicated; extract it into a shared utility (e.g., create a new
exported function getValidEnumValues in a common util module) and replace the
local implementations in packages/zod/src/coercer.ts (function
getValidEnumValues) and packages/zod/src/converter.ts with imports from that new
module, ensure the new util is exported, import paths are updated, and run
tests/typechecks to confirm no breaking changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/zod/src/coercer.ts`:
- Around line 31-38: The getValidEnumValues helper is duplicated; extract it
into a shared utility (e.g., create a new exported function getValidEnumValues
in a common util module) and replace the local implementations in
packages/zod/src/coercer.ts (function getValidEnumValues) and
packages/zod/src/converter.ts with imports from that new module, ensure the new
util is exported, import paths are updated, and run tests/typechecks to confirm
no breaking changes.

In `@packages/zod/src/zod4/coercer.native.test.ts`:
- Around line 9-17: The file declares NumericEnum and MixedEnum but never uses
them; either remove those unused enum declarations or add tests that exercise
them analogous to the existing TestEnum cases—specifically add unit tests that
import/define NumericEnum and MixedEnum and assert coercion/validation behavior
using the same test patterns as for TestEnum (copy the structure of the TestEnum
test blocks and substitute NumericEnum and MixedEnum to cover numeric-only and
mixed string/numeric enum coercion scenarios).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d8a3517c-2928-46e9-a376-6c5f8e7a500d

📥 Commits

Reviewing files that changed from the base of the PR and between 2e89be2 and 0c0ce10.

📒 Files selected for processing (7)
  • packages/zod/src/coercer.test.ts
  • packages/zod/src/coercer.ts
  • packages/zod/src/converter.test.ts
  • packages/zod/src/converter.ts
  • packages/zod/src/zod4/coercer.native.test.ts
  • packages/zod/src/zod4/converter.native.test.ts
  • packages/zod/src/zod4/converter.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/zod/src/zod4/converter.ts
  • packages/zod/src/converter.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working javascript Pull requests that update javascript code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Zod string literal enums are generated in OpenAPI spec without a string type

2 participants