Const Enums and Alternatives
Const enum inlining, package-boundary hazards, and string literal unions as the usual alternative.
const enum usually inlines values at use sites and emits no runtime object. That optimization is fragile across package boundaries.
Inlining is useful only when the whole project is compiled consistently.
const enum Axis {
X = "x",
Y = "y",
Z = "z",
}
function rotate(axis: Axis, degrees: number): string {
return `rotate ${degrees} on ${axis}`;
}
console.log(rotate(Axis.X, 90));String literal unions often give the same safety with no emit, no import, and natural JSON values.
type Role = "admin" | "member" | "guest";
function greet(role: Role): string {
return role === "admin" ? "Welcome, admin." : `Hello, ${role}.`;
}
const payload = { userId: "u-1", role: "admin" as Role };
console.log(JSON.stringify(payload));In production
Use const enum only inside a single TypeScript package compiled by one
toolchain. Avoid ambient const enums in published declarations, and prefer
string literal unions for external contracts.
Enjoyed this? Get more software craft delivered to your inbox.