graphql-code-generator icon indicating copy to clipboard operation
graphql-code-generator copied to clipboard

Typescripts enumsAsTypes option should derive their unions from a tuple with all the values

Open JesseZomer opened this issue 1 year ago • 1 comments

Is your feature request related to a problem? Please describe.

I like the option enumsAsTypes because I like working with string unions more in my code. However sometimes I need to be able to loop through all the values. That isn't possible unless the union type was derived from a tuple with the values.

an example:

enum Color {
    RED
    BLUE
}

produces

export enum Color {
  Red = 'RED',
  Blue = 'BLUE'
}

with this I could do Object.values(Color) and this would give me an array ['RED', 'BLUE']. However when I use enumsAsTypes: true I get

export type Color =
  | 'RED'
  | 'BLUE';

and I can't loop over these.

Describe the solution you'd like

when enumsAsTypes is true I would like for the input to not be:

export type Color =
  | 'RED'
  | 'BLUE';

but:

export const ColorValues = ['RED', 'BLUE'] as const;
export type Color = typeof ColorValues[number];

that way I can use ColorValues to loop over the values

Describe alternatives you've considered

No response

Is your feature request related to a problem? Please describe.

No response

JesseZomer avatar Sep 21 '23 10:09 JesseZomer

That would reduce a ton of boilerplate we need to write right now.

molinch avatar Feb 07 '24 15:02 molinch