cloudflare / chanfana

OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!
https://chanfana.pages.dev
MIT License
342 stars 43 forks source link

ZodObject has all properties optional #184

Open Carl-Foster opened 2 weeks ago

Carl-Foster commented 2 weeks ago

For some reason, all inferred types of ZodObject have the properties as optional. This is particularly annoying when extracting a type from a discriminated union.

const zContentPageNode = z.discriminatedUnion("type", [
  z.object({
    type: z.literal("component"),
    componentVersion: z.string().ulid(),
    content: z.record(z.unknown()),
  }),
  z.object({
    type: z.literal("formattedText"),
    content: z.record(z.unknown()),
  }),
]);

type zContentPageNode = z.infer<typeof zContentPageNode>;
type ComponentNode = Extract<zContentPageNode, { type: "component" }>;
// expect: { type: "component", componentVersion: string, content: Record<string, unknown> }
// actual: never

Without chanfana, this works as expected

TypeScript version 5.6.3 zod 3.23.8 hono 4.6.9 chanfana 2.1.0

Carl-Foster commented 2 weeks ago

Nevermind, looks like it was due to my tsconfig not setting strict: true.

Carl-Foster commented 2 weeks ago

The reason I noted this here was due to creating the application through the create-cloudflare method. The OpenAPI rest application starter has strict:false

G4brym commented 2 weeks ago

I've reopened the issue, to remember to update the create-cloudflare template later Thanks for finding this @Carl-Foster