Apollo-tooling: apollo client:codegen Option for different TypeScript enum output

Created on 23 Feb 2019  路  6Comments  路  Source: apollographql/apollo-tooling

Currently, the following GraphQL type

enum Color {
  RED
  BLUE
}

generates the following TypeScript type

export enum Color {
  RED = "RED",
  BLUE = "BLUE",
}

I would like to have the option to generate the following type instead:

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

This definition provides the same safety, but is more efficient and works better with TypeScript structural typing.

Unrelated: consider generating const enum instead of enum.

馃 codegen

Most helpful comment

I've fixed this in #1750 馃檮

All 6 comments

Related:

  • #193 - [TS] Use Typescript string enum for enums
  • #247 - Use TypeScript string enums

+1, having an enum is annoying for me. I don't want to import the enum and to Enum.Value, I just want to use string literals, it's as safe as enums and works nicely

247 was a mistake IMO. String enums should only really be used when you want the underlying string value to be opaque, and that isn't a feature that GraphQL can provide. This would maybe be a good idea if you could produce stable key names, but the key names are going to change just as often as the string values themselves, so there's no point.

String enums still have a slight advantage in that you can find all usages of it. String constants actually can be searched by "find all usages", which was a nice surprise (:tada:), but typescript can't distinguish "intentional" uses from "coincidental" uses of a given string constant -- the string enums work to disambiguate them, especially if there are multiple different enums in your schema that happen to partially overlap in some of the values; it would be good to know _which_ enum is being referred to when the value appears in code.

I think this might be mitigated by the planned "unique types" feature, but I haven't seen if it can be made to work for this use case.

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

These also work better if you have a js codebase and are using checkjs, there is no way (AFAIK) to import and use the typescript enum.

I've fixed this in #1750 馃檮

Was this page helpful?
0 / 5 - 0 ratings

Related issues

patrys picture patrys  路  3Comments

clayne11 picture clayne11  路  3Comments

lirbank picture lirbank  路  3Comments

ethansinjin picture ethansinjin  路  3Comments

arthens picture arthens  路  3Comments