Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way to create a zod validator for a list of literal strings #2885

Closed
SonofNun15 opened this issue Oct 19, 2023 · 1 comment
Closed

Best way to create a zod validator for a list of literal strings #2885

SonofNun15 opened this issue Oct 19, 2023 · 1 comment

Comments

@SonofNun15
Copy link

SonofNun15 commented Oct 19, 2023

I want to do something like this:

export const levels = ['level1', 'level2', 'level3', 'level4'] as const;

export const levelValidator = z.union(
  levels.map(l => z.literal(l))
);

export type Level = z.infer<typeof levelValidator>;

Goal is to create a list of literal strings and enforce that the property contains one of these strings.

I could certainly do:

z.union([
  z.literal('level1'),
  z.literal('level2'),
  z.literal('level3'),
  z.literal('level4'),
]);

But I want to have an array of these values that I can render as the options for a select input.

That map doesn't work because the type definition for union is so strict that it enforces that the array has at least 2 elements. This array does, but the compiler can't enforce that.

Any suggestions on the best way to proceed?

This issue is similar:
#2691

But I can't imagine using ~100 lines of code for this.

@JacobWeisenburger
Copy link
Contributor

Repository owner locked and limited conversation to collaborators Oct 21, 2023
@JacobWeisenburger JacobWeisenburger converted this issue into discussion #2890 Oct 21, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants