StefanTerdell / json-schema-to-zod

ISC License
322 stars 46 forks source link

Support strict option for zod object #70

Closed ezze closed 11 months ago

ezze commented 1 year ago

Consider the following type DateRangeExtended:

type DateRange = { from?: number; to?: number };

enum DateRangeType  {
  today = 1,
  yesterday = 2,
  tomorrow = 3
}

export type DateRangeExtended = DateRange | { type: DateRangeType };

The generated zod schema:

import { z } from "zod";

export default z
  .union([
    z
      .object({
        from: z.number().optional(),
        to: z.number().optional(),
      })
      .catchall(z.never()),
    z
      .object({
        type: z.union([
          z.literal(1),
          z.literal(2),
          z.literal(3)
        ]),
      })
      .catchall(z.never()),
  ])

Now when the data is parsed I get an empty object because DateRange allows empty properties and other properties are not prohibited by generated schema:

const result = schema.safeParse({ type: 1 });
if (result.success) {
  console.log(result.data); // => { }
}

It would be useful if this library supported strict option.

StefanTerdell commented 11 months ago

Duplicate #67