Skip to content

z.enum inside of z.tuple gives error "TypeError: Cannot convert undefined or null to object" #368

Description

@gersomvg

z.enum inside of z.tuple gives error: "TypeError: Cannot convert undefined or null to object"

Reproduction:

/**
 * Minimal reproduction of a bug in @asteasolutions/zod-to-openapi v8.4.3 with Zod v4.
 */
import { describe, it, expect } from "vitest";
import { z } from "zod";
import { extendZodWithOpenApi } from "@hono/zod-openapi";
import {
  OpenAPIRegistry,
  OpenApiGeneratorV3,
} from "@asteasolutions/zod-to-openapi";

extendZodWithOpenApi(z);

function generateDoc(schema: z.ZodType) {
  const registry = new OpenAPIRegistry();
  registry.registerPath({
    method: "post",
    path: "/test",
    request: {
      body: { content: { "application/json": { schema } } },
    },
    responses: { 200: { description: "ok" } },
  });
  return new OpenApiGeneratorV3(registry.definitions).generateDocument({
    openapi: "3.0.0",
    info: { title: "test", version: "1" },
  });
}

describe("zod-to-openapi bug: z.enum().nullable() inside z.tuple()", () => {
  it("works: z.enum() alone in a tuple", () => {
    const schema = z.tuple([z.enum(["a", "b"])]);
    expect(() => generateDoc(schema)).not.toThrow();
  });

  it("works: z.enum().nullable() outside a tuple", () => {
    const schema = z.enum(["a", "b"]).nullable();
    expect(() => generateDoc(schema)).not.toThrow();
  });

  it("works: z.string().nullable() inside a tuple", () => {
    const schema = z.tuple([z.string().nullable()]);
    expect(() => generateDoc(schema)).not.toThrow();
  });

  it("FAILS: z.enum().nullable() inside a tuple", () => {
    const schema = z.tuple([z.enum(["a", "b"]).nullable()]);
    // TypeError: Cannot convert undefined or null to object
    expect(() => generateDoc(schema)).not.toThrow();
  });

  it("FAILS: z.enum().nullable() inside an object inside a tuple", () => {
    const schema = z.tuple([
      z.object({ value: z.enum(["a", "b"]).nullable().optional() }),
    ]);
    // TypeError: Cannot convert undefined or null to object
    expect(() => generateDoc(schema)).not.toThrow();
  });
});

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions