Skip to content

Commit e333fbd

Browse files
committed
fix: const enums + isolatedModules emit invalid code
In `isolatedModules` mode, the compiler does not inline const enums, but also decides not to `import` them, leaving invalid code that throws a `ReferenceError` at runtime. This code: ``` import { SomeEnum } from './bar'; sink(SomeEnum.VALUE); ``` ..should compile to either: ``` var { SomeEnum } = require('./bar'); sink(SomeEnum.VALUE); ``` ..or (with const enum inlining): ``` sink(1 /* VALUE */); ``` ..but actually compiles to: ``` sink(SomeEnum.VALUE); ``` ..with no imports, which throws a ReferenceError at runtime. --- The compiler has already realised that the symbol is a referenced const enum, it just doesn't use this information when it comes to deciding whether to emit an import. This commit additionally checks that information, if we are compiling in isolatedModules mode. --- In my opinion, this is not the correct fix, but it is the simplest. In `isolatedModules` mode, `const enum` should probably be a compile error (because there are no benefits and the complexity is high, and, apparently, buggy). If not, the compiler should not be checking whether something is a const enum, and should just be treating it as a regular enum, and checking as if it was? Fixes microsoft#40499.
1 parent 5abc363 commit e333fbd

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

src/compiler/checker.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38263,7 +38263,8 @@ namespace ts {
3826338263
function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean {
3826438264
if (isAliasSymbolDeclaration(node)) {
3826538265
const symbol = getSymbolOfNode(node);
38266-
if (symbol && getSymbolLinks(symbol).referenced) {
38266+
const links = symbol && getSymbolLinks(symbol);
38267+
if (links?.referenced || (compilerOptions.isolatedModules && links?.constEnumReferenced)) {
3826738268
return true;
3826838269
}
3826938270
const target = getSymbolLinks(symbol!).target; // TODO: GH#18217

tests/baselines/reference/isolatedModulesImportConstEnum.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,5 @@ var Foo;
2121
//// [file1.js]
2222
"use strict";
2323
exports.__esModule = true;
24+
var file2_1 = require("./file2");
2425
console.log(file2_1.Foo.BAR);

0 commit comments

Comments
 (0)