microsoft / microsoft/TypeScript

Generated code when re-exporting a const enum inside a namespace using "preserveConstEnums": true leads to a runtime error

Open
#35,701 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: JS Emit Help Wanted
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.8.0-dev.20191216

Search Terms: const enum import export preserveConstEnums

Code

MyEnum.ts

const enum MyEnum {
    FirstValue,
    SecondValue
}
export default MyEnum;

ImportExportInNamespace.ts

import _MyEnum from "./MyEnum";
export namespace MyNamespace {
    export import MyEnum = _MyEnum;
}

App.ts

import { MyNamespace } from "./ImportExportInNamespace";
console.log(MyNamespace.MyEnum.FirstValue);

Compile the above using

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "preserveConstEnums": true
  }
}

Expected behavior:
ImportExportInNamespace.ts compiles to

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MyEnum_1 = require("./MyEnum");
var MyNamespace;
(function (MyNamespace) {
    MyNamespace.MyEnum = MyEnum_1.default;
})(MyNamespace = exports.MyNamespace || (exports.MyNamespace = {}));

Actual behavior:
ImportExportInNamespace.ts wrongly compiles to

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MyNamespace;
(function (MyNamespace) {
    MyNamespace.MyEnum = MyEnum_1.default;
})(MyNamespace = exports.MyNamespace || (exports.MyNamespace = {}));

i.e. we are missing

var MyEnum_1 = require("./MyEnum");

If I change the enum not to be a const the code compiles correctly. I'm using it as a workaround.

Related Issues:
#23514

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with MyEnum.ts, ImportExportInNamespace.ts, and App.ts using target es5, commonjs, and preserveConstEnums. Start by tracing the compiler's emitted output for the namespace export-import, then compare it with the expected ImportExportInNamespace.js output. Done means the generated file includes the require("./MyEnum") binding and the runtime example no longer errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.