graphql-zeus icon indicating copy to clipboard operation
graphql-zeus copied to clipboard

Generated "const enum OrderDirection" clashes with isolatedModules

Open iainmerrick opened this issue 2 years ago • 9 comments

I'm using Zeus to generate bindings in one NPM package, and attempting to import and use them in another package.

I'm hitting type errors around this generated code:

export declare const enum OrderDirection {
    asc = "asc",
    desc = "desc"
}

The problem is that many clients configure TS with isolatedModules: true, which leads to a type error on import:

error TS2748: Cannot access ambient const enums when the '--isolatedModules' flag is provided.

Using "asc" and "desc" directly in the client code doesn't work either, for reasons I can't quite fathom:

Type '"asc"' is not assignable to type 'OrderDirection | null | undefined'.

I don't fully understand why TypeScript can't be configured to handle this, but it seems like exporting const enums is generally considered bad practice:

  • Here's a good writeup: https://ncjamieson.com/dont-export-const-enums/
  • Unresolved discussion among the TS devs: https://github.com/microsoft/TypeScript/issues/40499

Can this be fixed by changing the exported declaration? I think this might work:

export type OrderDirection = "asc" | "desc"

iainmerrick avatar Jul 01 '22 11:07 iainmerrick

I can add some zeus config in the future. Exporting enums is considered bad practice, const enums are much lighter but get hidden during transpilation

aexol avatar Jul 01 '22 12:07 aexol

A lot of people asked for const enums before instead of enums

aexol avatar Jul 01 '22 12:07 aexol

How about avoiding enums entirely and just making it a union of strings?

iainmerrick avatar Jul 01 '22 13:07 iainmerrick

ok I'll try and test that with different projects and if it won't cause problems I will change it

aexol avatar Jul 01 '22 21:07 aexol

For the reasons explained by @iainmerrick and @aexol we were actually not able to use either enum or const enum on our project.

To avoid this, we patched this part and indeed used string unions. In the following screenshot, you can see our output on the left and the original Zeus output on the right: image

We've been using this on our codebase for a few months and are happy with it.

If this is something that looks good, I'm ready to do a PR to add this option using a flag. 🙂

It it can be useful for someone else, here's the commit on our fork to apply this change: elba-security/graphql-zeus@7b2c6cb (#6)

ValentinH avatar Sep 07 '22 10:09 ValentinH

Hello @aexol

Any news regarding this issue ? It would be nice to have an option during generation to satisfy everyone enum | const enum | union

Thank you.

dt-brahim-bouaboud avatar Apr 22 '24 13:04 dt-brahim-bouaboud

This week I will upload new zeus with config and option to generate different enums. Sorry for delay

aexol avatar Apr 24 '24 08:04 aexol