Skip to content

Extend typescript-enum-array with option for zod-supported string union #1243

@JamisonHolt

Description

@JamisonHolt

This is namely a request for making the typescript-enum-array plugin have a zod-friendly way of declaring array exports in a way that is easily mappable to string union type declarations as well. Consider the following:

type MyGeneratedUnion = 'foo' | 'bar' | 'baz';
export const MY_GENERATED_UNION = ['foo' | 'bar' | 'baz'] as const; // using the constArrays option

The above works somewhat well with zod's z.enum type inference, where z.enum(MY_GENERATED_UNION).parse(someVar) will be type-inferred as 'foo' | 'bar' | 'baz'.

Image

My main grievance is that any future devs inspecting a var will see the type as 'foo' | 'bar' | 'baz', which is harder to trace to the source. It's not clear at first glance that this is a generated string union from our GraphQL codegen. However, leaving constArrays disabled makes things worse:

Image

Now we've lost even more information for the variable type annotation, making it harder to trace back to the source AND less useful for design patterns like switch-case exhaustiveness.

As a result, I'd like to propose a configuration option that would let us generate more zod-compatible, tuple declarations. For example:

Image

I hope it's clear why this would be nice. In a large codebase, it can easily become harder for devs to track down where a type's definition comes from. Having the ability for zod to provide the named type makes tracking down the declaration much easier, especially for junior devs or anyone who's still ramping up.
I'm down to own this change, and here is a very rough idea of what it might look like: f60bd5f

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