-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Restrict z.enum options to existing type #2280
Comments
Perhaps we can update Line 3918 in 51e14be
into this? export type EnumValues<T extends string = string> = [T, ...T[]]; |
Another option would be to update EnumValues to be less restrictive: export type EnumValues = string[]; // and similar updates in createEnum() then the validation works just fine with simple type Status = 'new' | 'accepted' | 'closed'
z.enum(['new', 'accepted'] satisfies Status[]) // OK
z.enum(['new', 'approved'] satisfies Status[]) // Error: Type 'string' does not satisfy the expected type 'Status[]' In #2312, @igalklebanov told that allowing |
Allow statically validate enum values against external type. Fix colinhacks#2280.
Making EnumValues generic (see linked PR) is fully backwards compatible. From what I have discovered |
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. |
There is a PR for implementing this improve which makes no harm. |
Passing a generic into Generally speaking, you aren't supposed to start with a type then try to write a Zod schema that's compatible with it. The goal is to define your types with Zod, so it's often inconvenient to go the other direction. This is one of those cases. In the meantime I recommend using your own type Status = "pending" | "fulfilled" | "rejected";
type Tuple<T extends string> = [T, ...T[]];
const myEnum: z.ZodEnum<Tuple<Status>> = z.enum([
"pending",
"fulfilled",
"rejected",
]); |
* feat: make EnumValues generic Allow statically validate enum values against external type. Fix #2280. * Docs --------- Co-authored-by: Colin McDonnell <[email protected]>
Problem
I want to restrict options passed to
z.enum
to the existing type.Is there an elegant way to statically validate the typings of enum options?
Solutions tried
at least a built-in helper would be useful:
The text was updated successfully, but these errors were encountered: