Typescript: Why does TypeScript PM advice not to use const enum? If so, why not take out from language SPEC

Created on 26 Mar 2019  ·  7Comments  ·  Source: microsoft/TypeScript

Why does TypeScript PM advice not to use const enum? If so, why not take out from language SPEC

https://github.com/facebook/create-react-app/pull/4837#issuecomment-430107471

Unactionable

Most helpful comment

P.S. I have a name.

All 7 comments

Mistakes were made, depending on how you look at it. Wholesale cutting features out of the language is not something we do.

Is there any improvement that could be made to https://www.typescriptlang.org/docs/handbook/enums.html to possibly steer new users away from or at least keep them mindful of the issues with const enum?

Why does TypeScript PM advice not to use const enum?

@DanielRosenwasser didn't say don't use const enums, just use them appropriately. The problem is that it causes the TypeScript compiler to "hard code" all the values, fully erasing the enum, which, when using a self contained library where that enum won't be leaked outside of that code base is slightly more runtime efficient. Most cases though, you don't want the enum fully erased at runtime.

I think @nattthebear's suggestion is a good one, though the handbook basically says "use regular enums unless..." already:

In most cases, enums are a perfectly valid solution. However sometimes requirements are tighter. To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it’s possible to use const enums.

And it talks about how they are fully erased. I guess the only thing it doesn't say is they should be limited in use to "internal" enums.

P.S. I have a name.

Const enums are more performant and especially handy, as @kitsonk mentioned, for internal enums. I don't think mistakes were made. I am glad const enums are available.

I don't think mistakes were made.

The feature definitely is useful, but the fact that Babel can't do this is part of what makes the design questionable. A better design in retrospect might have been a mode where enums in TS files could be inlined as a compile-time opt-in so that you could get the efficiency gains you care about while avoiding the issues in #5219, while also allowing the feature to work where tools only process a single file at a time.

@DanielRosenwasser That is a design flaw on the part of the library developer, not TypeScript. Allowing this feature also allows things like translating existing APIs which return numeric enums into TypeScript enums (which are more readable than checking if x===1 and just commenting what it means), while maintaining the efficiency of the less readable version.

Was this page helpful?
0 / 5 - 0 ratings