TypeScript
TypeScript copied to clipboard
Cannot use `const enum` to define an interface key in `isolatedModules` mode
Bug Report
I am maintaning a library where I use const enum
variants to declare the keys of an interface (interface Foo { [MyConstEnum.Foo]: "bar" }
). The enum and the interface are in the same module.
It works well, but once compiled using tsc
and included in a user project using isolatedModules: true
, TypeScript fails with the following error:
Error: [...].d.ts: error TS2748: Cannot access ambient const enums when 'isolatedModules' is enabled.
I don't understand why this usage is restricted, since the enum is only used in a type definition, and both are present in the same .d.ts
file.
🔎 Search Terms
Cannot access ambient const enums when the '--isolatedModules' flag is provided. TS2748 interface
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about isolated modules and const enum
⏯ Playground Link
Playground link with relevant code
💻 Code
- Using
isolatedModules: true
- In a
.d.ts
file
declare const enum EventName {
FOO = 1,
BAR = 2
}
type EventMap = {
[EventName.FOO]: number;
[EventName.BAR]: string;
};
🙁 Actual behavior
TS fails with the following error:
Error: [...].d.ts: error TS2748: Cannot access ambient const enums when 'isolatedModules' is enabled.
🙂 Expected behavior
TS succeeds
Workaround
As a workaround, I declare a fake object using the same keys and values as the enum
, and then use this to declare the interface
:
declare const enum EventName {
FOO = 1,
BAR = 2
}
declare const EventNameAsConst: {
FOO: EventName.FOO
BAR: EventName.BAR
}
type EventMap = {
[EventNameAsConst.FOO]: number;
[EventNameAsConst.BAR]: string;
};
This works, but it is a bit cumbersome to have to maintain this intermediary object.