Skip to content

Commit 6fcd94d

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 34162ad commit 6fcd94d

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
@@ -38211,7 +38211,8 @@ namespace ts {
3821138211
function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean {
3821238212
if (isAliasSymbolDeclaration(node)) {
3821338213
const symbol = getSymbolOfNode(node);
38214-
if (symbol && getSymbolLinks(symbol).referenced) {
38214+
const links = symbol && getSymbolLinks(symbol);
38215+
if (links?.referenced || (compilerOptions.isolatedModules && links?.constEnumReferenced)) {
3821538216
return true;
3821638217
}
3821738218
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)