āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā š typescript/enums ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā
TypeScript enums let you name related constants with a compact syntax while keeping compile-time checking and JavaScript output. They compile to JavaScript objects, so you can reference them at runtime and inspect their values.
enum Direction {
Up, // 0
Down, // 1
Left = 10,
Right // 11 (auto-increment)
}
let dir: Direction = Direction.Up;
Key traits:
Direction[0] === "Up").enum Role {
Admin = "admin",
Staff = "staff"
}
Highlights:
const enum Status {
Loading,
Ready,
Error
}
const message = Status.Ready; // compiled to literal 1
Use const enum to inline literal values and erase the enum object from emitted JavaScript. This reduces bundle size, but you lose runtime introspection. Avoid when you need reverse mapping or dynamic access.
Bundlers that perform isolated transpilation (ts-node/register, swc, babel) may not support const enums unless they run the TypeScript compiler pipeline. Consider
preserveConstEnumsif you must keep the enum object in JS while still declaringconst enum.
Declare shape-only enums in .d.ts files with the declare enum syntax when the values come from external scripts. Ambient members default to numbers and allow constant or computed initializers. The compiler does not emit code for ambient enums.
enum Result {
Ok = 1,
Failure = "fail"
}
Mixing strings and numbers is legal but confusing. Prefer distinct enums or union types instead.
Union literals are often more ergonomic when you do not need runtime access:
type Direction = "up" | "down" | "left" | "right";
Because numeric enums are actual objects, you can iterate keys:
for (const key in Direction) {
if (isNaN(Number(key))) {
console.log(key); // "Up", "Down", ...
}
}
String enums only expose named keys, so iteration is simpler:
Object.values(Role); // ["admin", "staff"]
const enum or union literals in performance-sensitive code to avoid extra objects..d.ts unless the runtime truly provides them.type Status = StatusEnum.Loading | StatusEnum.Ready | StatusEnum.Error;.Enum member must have initializer: string enums require an explicit value.Cannot access 'X' before initialization: circular dependencies between enums and other values can cause runtime ReferenceError. Hoist enums or refactor modules.ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā