zod icon indicating copy to clipboard operation
zod copied to clipboard

Feature Request: Less strict enum / oneOf

Open sbking opened this issue 3 years ago • 2 comments

Right now z.enum only works when you have a constant/static array of strings:

const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;

But this doesn't work for dynamic arrays:

declare const fish: string[];
const Fish = z.enum(fish);
// ts-error: Argument of type 'string[]' is not assignable to parameter of type '[string, ...string[]]'.

It also doesn't work for arrays of other primitive types:

const months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;
const Month = z.enum(months);
// ts-error: Argument of type 'readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]' is not assignable to parameter of type '[string, ...string[]]'.

It's possible to solve this with refine:

const Fish = z.string().refine((value) => fish.includes(value));
const Month = z.number().refine((value): value is typeof months[number] => months.includes(value));

However other libraries like Yup provide a convenient oneOf method for these cases:

const Fish = yup.string().oneOf(fish);
const Month = yup.number().oneOf(months);
const Mixed = yup.mixed().oneOf(['foo', 42, true]);

Is there any appetite to add a less strict version of enum / oneOf to Zod?

sbking avatar Sep 10 '22 20:09 sbking

A project that I'm working on generates zod validators from an openapi spec. One of the schema objects is an enum of integers like [512, 2048, 4096].

EDIT: Looks like my case is a duplicate of https://github.com/colinhacks/zod/issues/1118

zephraph avatar Sep 27 '22 01:09 zephraph

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Nov 26 '22 02:11 stale[bot]