8000 Restrict z.enum options to existing type · Issue #2280 · colinhacks/zod · GitHub
[go: up one dir, main page]

Skip to content
Restrict z.enum options to existing type #2280
@IlyaSemenov

Description

@IlyaSemenov

Problem

I want to restrict options passed to z.enum to the existing type.

type Status = 'new' | 'accepted' | 'closed'

z.enum(['new', 'accepted']) // OK
z.enum(['new', 'approved']) // Invalid choice - should be somehow disallowed

Is there an elegant way to statically validate the typings of enum options?

Solutions tried

z.enum(['new', 'accepted'] as Status[]) // Argument of type 'Status[]' is not assignable to parameter of type '[string, ...string[]]'.
z.enum(['new', 'accepted'] satisfies Status[]) // Argument of type '("new" | "acepted")[]' is not assignable to parameter of type '[string, ...string[]]'.
z.enum<Status>(['new', 'accepted']) // Expected 2 type arguments, but got 1
z.enum(['new', 'accepted'] as [Status, ...Status[]]) // works, but ugly
z.enum(['new', 'accepted'] satisfies [Status, ...Status[]]) // works, but ugly
z.enum(['new', 'accepted'] as const satisfies readonly Status[]) // works, but could it be simpler?

at least a built-in helper would be useful:

z.enum(['new', 'accepted'] as z.EnumOptions<Status>) // self explanatory

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0