colinhacks / tozod

MIT License
153 stars 7 forks source link

Support for literal types #16

Open boredland opened 2 years ago

boredland commented 2 years ago

Hi there!

When using toZod on this interface:

export type Position = [number, number];

export interface Polygon {
    type: "Polygon";
    coordinates: [Position[],Position[]];
    bbox?: [number, number, number, number] | [number, number, number, number, number, number]
}

I stumble across the missing support for unions (https://github.com/colinhacks/tozod/issues/4), because I neither can use a tuple .or another, nor an array.

And I can't set a literal for "type", because toZod expects "never" instead of a literal.

I'd expect this to be a strict match for it:

export const polygonValidation = z.object({
  type: z.literal('Polygon'),
  coordinates: z
    .array(z.array(z.tuple([z.number(), z.number()])).min(4))
    .min(1)
    .max(2),
  bbox: z
    .union([
      z.tuple([z.number(), z.number(), z.number(), z.number()]),
      z.tuple([
        z.number(),
        z.number(),
        z.number(),
        z.number(),
        z.number(),
        z.number(),
      ]),
    ])
    .optional(),
});