cometkim / gatsby-plugin-typegen

Let's give developers using GatsbyJS better DX with extreme type-safety
https://www.gatsbyjs.org/packages/gatsby-plugin-typegen/
MIT License
204 stars 23 forks source link

Access generated enum values #78

Closed JosXa closed 4 years ago

JosXa commented 4 years ago

The plugin generates the following code:

enum GraphCMS_ReleaseKind {
  Full = 'Full',
  InsiderBuild = 'InsiderBuild',
  PreviewBuild = 'PreviewBuild'
}

for this schema (introspection.json):

      {
        "kind": "ENUM",
        "name": "GraphCMS_ReleaseKind",
        "description": null,
        "fields": null,
        "inputFields": null,
        "interfaces": null,
        "enumValues": [
          {
            "name": "Full",
            "description": null,
            "isDeprecated": false,
            "deprecationReason": null
          },
          {
            "name": "InsiderBuild",
            "description": null,
            "isDeprecated": false,
            "deprecationReason": null
          },
          {
            "name": "PreviewBuild",
            "description": null,
            "isDeprecated": false,
            "deprecationReason": null
          }
        ],
        "possibleTypes": null
      },

and I am having troubles accessing the enum values, most likely due to global declaration namespaces being compiled away during the build process (as a result of https://github.com/cometkim/gatsby-plugin-typegen/pull/47):

const isInsiderBuild = displayedRelease.releaseKind === GatsbyTypes.GraphCMS_ReleaseKind.InsiderBuild;

... results in: Uncaught ReferenceError: GatsbyTypes is not defined (only at runtime).

The whole purpose of Enum types is to be able to do type-safe comparisons, so not being able to import them isn't helpful. Maybe I'm missing something and that is indeed possible, but I wouldn't know how.

But I also see that exporting this member from the global declarations file might go against the philosophy of that file, so I'm suggesting to maybe also generate a second file with all the importable constants such as the enums?

cometkim commented 4 years ago

Hi @JosXa, thanks for reporting!

Ideally in GatsbyJS, the actual behavior is always just a string and only the type information is actually needed. So, I think === 'InsiderBuild' is enough for it, or do I miss something here.

Can you share the example of schema customization that generates this enum type? I will test it and change the generated result to be const enum.

cometkim commented 4 years ago

Providing code to be used at runtime is not the goal of this project. So, this will be prevented in the next version.

But please feel free to reopen this if you have case actually need this. :)