Skip to content

Conversation

@sentik
Copy link
Contributor

@sentik sentik commented Oct 28, 2025

Fix TypeScript type error for arrays with enum and default values (#2427)

Problem

When generating Zod validators for arrays of string enums with default values, TypeScript reports type incompatibility errors. The generated default variable is typed as string[] instead of the expected ("A" | "B" | "C")[].

Before:

export const postEnumBodySomeEnumDefault = ["A"];

export const postEnumBody = zod.object({
  "some_enum": zod.array(zod.enum(['A', 'B', 'C'])).default(postEnumBodySomeEnumDefault)
  // Type error: Type 'string[]' is not assignable to type '("A" | "B" | "C")[]'
})

Solution

Added type inference logic to detect when a schema is an array with enum items. When this condition is met, the default value is suffixed with as const to ensure proper TypeScript typing:

const isArrayWithEnumItems = 
  Array.isArray(schema.default) && 
  type === 'array' && 
  schema.items && 
  'enum' in schema.items;

if (isArrayWithEnumItems) {
  defaultValue = `${defaultValue} as const`;
}

After:

export const postEnumBodySomeEnumDefault = ["A"] as const;
// Now TypeScript correctly types this as ("A")[]

@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 03b3c0b 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
melloware pushed a commit that referenced this pull request Oct 30, 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: TypeScript issue with default value for Zod enum validator

2 participants