Description
For some reason TypeScript enum values are transpiled differently with ts-node than with tsc. This can lead to runtime errors if the used enum doesn't exist at runtime.
Here's an example: the current typings for big.js
define an enum that doesn't actually exist in the JS library:
// node_modules/@types/big.js/index.d.ts
export const enum Comparison {
GT = 1,
EQ = 0,
LT = -1,
}
This enum doesn't exist at runtime:
console.info(require('big.js').Comparison)
// undefined
Now, let's say we have this TS code:
import {Comparison} from 'big.js'
Comparison.LT.toString()
tsc transpiles it to this (using a sane tsconfig.json with ES2017 target):
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-1 /* LT */.toString();
Note that there's no require
calls anywhere and the enum value -1
is inlined with a comment included. Running the generated JS file with node doesn't throw any exceptions.
Now, running the same TS file with ts-node gives me this:
/home/joonas/enum-bug/main.ts:3
Comparison.LT.toString()
^
TypeError: Cannot read property 'LT' of undefined
at Object.<anonymous> (/home/joonas/enum-bug/main.ts:3:12)
at Module._compile (module.js:643:30)
at Module.m._compile (/home/joonas/enum-bug/node_modules/ts-node/src/index.ts:423:6)
at Module._extensions..js (module.js:654:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/joonas/enum-bug/node_modules/ts-node/src/index.ts:426:4)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at Object.<anonymous> (/home/joonas/enum-bug/node_modules/ts-node/src/_bin.ts:177:12)
After adding some logging to ts-node inside my node_modules, I can see that this is the transpiled output:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const big_js_1 = require("big.js");
big_js_1.Comparison.LT.toString();
Note the require
call and how the enum value is not inlined but accessed at runtime.
Any ideas? This might of course be a misconfiguration in my part, a TS compiler bug, or a problem with the compiler API.
$ node --version
v8.9.4
Library versions:
"dependencies": {
"@types/big.js": "4.0.2",
"big.js": "5.0.3",
"ts-node": "4.1.0",
"typescript": "2.6.2"
}