Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `const enum` allowed with `isolatedModules`?

Tags:

typescript

declare const enum {
    UP,
    DOWN,
}`

isn't allowed when the --isolatedModules compilerOption is used.

error TS1209: Ambient const enums are not allowed when the '--isolatedModules' flag is provided.

My understanding of --isolatedModules is that it tells the compiler to do extra checking to ensure that separate compilation (such as by using transpileModule) is safe.

So why is const enum (without declare) allowed? Isn't it unsafe for separate compilation? That is, if foo.ts imports and uses a const enum from bar.ts, how could ts.transpileModule know how to correctly transpile the enum usage?

like image 349
Max Heiber Avatar asked Jul 02 '19 14:07

Max Heiber


1 Answers

If you are using other transpilers to compile your code, for example babel, then that transpiler can only work with typescript declared in the same module file. If you declaring your const enum inside the same module that you are using it, then it's not a problem. The problem start when you want to expose your enum to other modules.

For example, if you are writing an enum:

const enum Animal {
  DOG,
  CAT
}

So far it's not a problem if you will just use this code in the SAME source file that you declare it:

Animal.DOG // Will be replaced with 0.

But image that you want to use Animal.DOG in another source file. With transpiler compilation happening on an isolated-module basis:

  • the compiler reads a typescript module.
  • the module’s type information is stripped.
  • what’s left is the JavaScript module that the compiler writes.

so it's not possible to know what is Animal.DOG if it's not been declared on the same module. That's why the flag is called --isolatedModules in the first place. This flag is checking and reporting any typescript use that'll not work in this case.

If you are writing a library then DON'T export const enum because your users will not be able to use them if they are using babel to compile their code instead of tsc.

like image 114
Ziv Barber Avatar answered Nov 08 '22 12:11

Ziv Barber