Hacker News new | ask | show | jobs
by OscarDC 517 days ago
A particularly ugly but useful feature of "const enum" (sadly, the "const" flavor of enums are not referred to in this documentation), is that it's the only way to declare a compile-time constant in TypeScript.

e.g. for "development" vs "production" environments, you could write a declaration file for each of those envs as such:

  // production.d.ts

  declare const enum ENVIRONMENT {
    PROD = 0,
    DEV = 1,
    CURRENT_ENV = PROD,
  }
And then write in your code something like:

  // some_file.ts
  if (ENVIRONMENT.CURRENT_ENV === ENVIRONMENT.DEV) {
    // do something for dev builds
  }
It will be replaced by TypeScript at compile-time and most minifiers will then be able to remove the corresponding now-dead code when not in the right env.

This is however mainly useful when you're a library developer, as you may not have any "bundler" dependency or any such complex tool able to do that task.

Here, the alternative of bringing a complex dependency just to be able to replace some constants is not worth its cost (in terms of maintenance, security, simplicity etc.), so even if `const enum`s may seem poorly-adapted, they are actually a good enough solution which just works.