Skip to content

Commit 3cb234b

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 a14a02c commit 3cb234b

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
@@ -38217,7 +38217,8 @@ namespace ts {
3821738217
function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean {
3821838218
if (isAliasSymbolDeclaration(node)) {
3821938219
const symbol = getSymbolOfNode(node);
38220-
if (symbol && getSymbolLinks(symbol).referenced) {
38220+
const links = symbol && getSymbolLinks(symbol);
38221+
if (links?.referenced || (compilerOptions.isolatedModules && links?.constEnumReferenced)) {
3822138222
return true;
3822238223
}
3822338224
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)