question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

const enum not being converted to number

See original GitHub issue

This has been an issue since at least 3.0. I have lots of enums defined this way:

namespace SkycourtApi {
    export const enum RoundRobinCompetitorStatus {
        Active = 0,
        Injured = 1,
        DropOut = 2
    }
}

then in my code I use them like this: this.playerNotActive = model.Status !== SkycourtApi.RoundRobinCompetitorStatus.Active;

99% of the time this will get converted to the number 0 properly. But occasionally this will get left as the identifier: SkycourtApi.RoundRobinCompetitorStatus.Active

I compile my TS code twice, once for unit tests and that uses module: “amd” and once for production that uses module:“esnext” The strange thing is that I have never encountered this problem in my unit tests. I have only ever encountered this problem when creating the production code with module: “esnext”. Here is my tsconfig file that causes the problem. The only difference between the production and unit test config files is module and removeComments (true in unit test and false in production - yes I typed that correctly. The comments are removed later when webpacking).

{
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "esnext",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "typeRoots": [
      "../node_modules/@types",
      "typings"
    ],
    "baseUrl": "Scripts/",
    "importHelpers": true,
    "lib": [
      "dom",
      "es5",
      "scripthost",
      "es2015.promise"
    ]
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules",
    "obj",
    "bin"
  ]
}

Now the really strange part, is that when this problem occurs, all I have to do is move the offending line up or down in the file and that usually fixes the problem and the production code will go back to converting the enum into the number 0.

Search Terms: const enums enum not converted to number enum not inlined Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.

Expected behavior: The const enums should always be converted to their numeric value.

Actual behavior: 1% of the time, they will be left as the identifier unless I move the line up or down one line in the file being compiled.

Playground Link: I will see if i can create a playground and comeback and link it here. It has been difficult to reproduce, especially since just moving the line up or down a line in the source file gets it to compile properly.

Related Issues: none

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
Brandon-Beckcommented, Oct 26, 2019

Possibly related. I found exported enums do not work with isolated modules and an es target. commonjs is happy for me, but only because it has no choice but to import everything. Not sure why it generates an enum object instead of a literal like it does without isolatedModules. Tested on 3.6.4 & 3.7.0-dev

test.zip

tsconfig.json

{
  "compilerOptions": {
    "target": "es5", 
    "module": "es2015", 
    "outDir": "./out",  
    "rootDir": "./src", 
    "esModuleInterop": true,
    "isolatedModules": true
  }
}

exportingFile.ts

export const enum ThreadType {
  CommentThread,
  DiscussionThread
}

export function cat(a: ThreadType) {
  if (a == ThreadType.CommentThread) {
    console.log('No. No cats. You suck!')
  }
  else {
    console.log('Ok. Sure. I can see how cats could be considered cute....')
  }
}

importingFile.ts

import {cat, ThreadType} from './exportingFile'

cat(ThreadType.CommentThread)

The output:

exportingFile.js

export var ThreadType;
(function (ThreadType) {
    ThreadType[ThreadType["CommentThread"] = 0] = "CommentThread";
    ThreadType[ThreadType["DiscussionThread"] = 1] = "DiscussionThread";
})(ThreadType || (ThreadType = {}));
export function cat(a) {
    if (a == ThreadType.CommentThread) {
        console.log('No. No cats. You suck!');
    }
    else {
        console.log('Ok. Sure. I can see how cats could be considered cute....');
    }
}

importingModule.js

import { cat } from './exportingFile';
cat(ThreadType.CommentThread);

Notice that:

  1. It generated an enum object instead of a numeric literal
  2. the output code obviously wont work (ThreadType is undefined).
  3. the code would work if it kept the import (or generated a literal like normal)
  4. tsc gives no errors nor warnings
0reactions
jablkocommented, Nov 3, 2021
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to get a const enum from value in typescript [duplicate]
I have two string enums that I'm trying to convert, one to the other, via value. The enum that I'm trying to get...
Read more >
Handbook - Enums - TypeScript
Computed and constant members · It is the first member in the enum and it has no initializer, in which case it's assigned...
Read more >
Enum.Parse Method (System) - Microsoft Learn
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Read more >
Convert an Enum to String or Number in TypeScript | bobbyhadz
NUMERIC Enums enum NumericEnum { Yes, No, Maybe, } // 👇️ to string const str1 = NumericEnum[NumericEnum.Yes]; console.log(str1); // 👉️ "Yes" // 👇️...
Read more >
How To Convert A TypeScript Enum To A JavaScript Array Or ...
What Are TypeScript Enums? 1. Numeric TypeScript Enum; 2. String TypeScript Enum; 3. Hetrogeneous TypeScript Enums. How To Get Single Value From ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found