Typescript offers `const enums` as a close alternative to compile-time constants, as noted in the documentation, stating that they are completely removed during compilation unlike regular enums.
However, there are drawbacks to using const enums, such as their incompatibility with the `isolatedModules = true` mode commonly used by bundlers.
Another limitation is that Typescript does not perform dead code elimination, requiring the use of external tools to remove branches like `if (0 === 1)` post-compilation.
To accommodate different enum definitions for the same type, separate `tsconfig.json` files must be utilized, each referencing a specific definition file.
tsconfig.browser.json
{
"files": [
"t.ts",
"target-enum-browser.d.ts"
]
}
target-enum-browser.d.ts
declare module 'target-enum' {
export const enum Target { Node, Browser, Current = Browser }
}
tsconfig.node.json
{
"files": [
"t.ts",
"target-enum-node.d.ts"
]
}
target-enum-node.d.ts
declare module 'target-enum' {
export const enum Target { Node, Browser, Current = Node }
}
t.ts
import {Target} from 'target-enum';
if (Target.Current === Target.Browser) {
console.log('browser');
} else if (Target.Current === Target.Node) {
console.log('node');
} else {
console.log('?');
}
Compiled using
tsc --project tsconfig.browser.json
"use strict";
exports.__esModule = true;
if (1 /* Current */ === 1 /* Browser */) {
console.log('browser');
}
else if (1 /* Current */ === 0 /* Node */) {
console.log('node');
}
else {
console.log('?');
}
Compiled using tsc --project tsconfig.node.json
"use strict";
exports.__esModule = true;
if (0 /* Current */ === 1 /* Browser */) {
console.log('browser');
}
else if (0 /* Current */ === 0 /* Node */) {
console.log('node');
}
else {
console.log('?');
}