Skip to content

zod: enum properties don't respect the "default" field #3726

@Chewie

Description

@Chewie

Description

When writing a schema like this:

schema:
  type: object
  properties:
    foo:
      type: string
      enum:
        - foo
        - bar
        - baz
      default: "foo"

The generated zod schema is as follows:

export const zTestBody = z.object({
  foo: z.enum(['foo', 'bar', 'baz']).optional(),
});

Note that the field foo does not have a default.
Instead, I expected to have this:

export const zTestBody = z.object({
  foo: z.enum(['foo', 'bar', 'baz']).optional().default('foo'),
});

I tried adding it with a resolver, but the ctx.schema only provides the following inside enum:

{
  type: 'enum',
  items: [
    { const: 'foo', type: 'string' },
    { const: 'bar', type: 'string' },
    { const: 'baz', type: 'string' },
  ],
  logicalOperator: 'or'
}

While a default value obviously can't work for basic typescript interfaces, this is something that a runtime validator could easily do, provided the field was preserved during parsing.

Cheers!

Reproducible example or configuration

https://stackblitz.com/edit/hey-api-example-vahwifxs?file=openapi.yaml,openapi-ts.config.ts,src%2Fclient%2Fzod.gen.ts

OpenAPI specification (optional)

openapi: 3.1.0
info:
  title: Test
  description: A description
  version: 1.0.0
servers:
  - url: "test.example.com"


paths:
  /test:
    post:
      operationId: test
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                foo:
                  type: string
                  enum:
                    - foo
                    - bar
                    - baz
                  default: "foo"
        required: true

System information (optional)

No response

Metadata

Metadata

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