Skip to content

Issue with enum initiated with Array<Something> type #3080

@jakubwolny

Description

@jakubwolny

I'm trying to migrate quite big types definitions library (100+ files) from superstruct to zod for following reasons

  • readonly()
  • discriminatedUnion()

So far it's been smooth ride I'm having issue with "enum" type. We mostly used 2 patterns in superstruct:

// (1) real enum
enum SomethingType {
  SOMETHING = 'SOMETHING'
}

// (2) fake enum 
const SomethingType = {
  SOMETHING: 'SOMETHING'
} as const

// both were used fine in superstruct enum - by simply converting then into Array of something
const sortedValues = Object.values(SomethingType) // Array<"SOMETHING">
const superstructEnum = enums(sortedValues)

export const zodEnum = z.enum(SomethingType) // error Argument of type SomethingType[] is not assignable to parameter of type readonly [string, ...string[]]

Why we used fake enum is a bit out of scope of this question, but if you're curious: for migrating between the versions where enum members change. The issue I'm having with zod is that none of these ways of defining enums seem to work. I guess it's all because of the requirement of having first element in the tuple:

createZodEnum<U extends string, T extends Readonly<[U, ...U[]]>>

can I ask - what's the reason or benefit of having this?

Also, I know I probably could change from enum() to union() but for this I need to define all these strings as literals, which is quite big change and affects the library's public API. Is there any other way to define the enum in zod, which is similar to the one in superstruct?

Would this PR #2338 fix my problem?

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