Hacker News new | ask | show | jobs
by cypressious 1614 days ago
Have you tried `const enum`?

See https://www.typescriptlang.org/docs/handbook/enums.html#cons...

> Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites.

1 comments

I remember reading somewhere that the TypeScript devs considered const enums to be a mistake and recommend against using them. I don't remember why, though.
const enums are one of the few cases where type information changes the emitted JS, something that's arguably a bigger problem than TypeScript-specific, but still just syntax sugar, syntax highlighted in the article.

Const enums are erased at compile time. If you have a reference to `MyEnum.VAR`, TS has to check whether the enum is a const enum, and if so, replace with something like `1 /* VAR */`. This means that the type information in one file (where the enum is defined) is necessary to determine the proper output of any file that uses it.

Thank you for the answer! I won't waste your time because I'm sure the answer is somewhere on the web, but off the top of my head, I don't understand why TS "has" to emit different JS. I would've assumed that the entire point of a const enum is to inline the raw value in the emitted JS, and thus, the programmer should be careful to remember/know that the code is dealing with raw ints/strings.
You potentially get a problem for every '.' expression. In this code:

  import {Something} from './file';
  console.log(Something.PROP);
TypeScript doesn't know what to emit without type information. If Something is a class, then the JS will look the same. But if it's a const enum, then TypeScript has to erase the Something.PROP expression and replace it with the constant value of that enum member, since Something will not exist at runtime.