~/
hackweb.dev
TypeScript Enums
Quiz
⌘K
...
~/
/tutorials
/ts/ts-enums/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/ts/7ts-enums
Write
Preview
Diff
# TypeScript Enums Enums define a set of named constants. They're TypeScript-only — not in JavaScript. ## Basic Syntax ```typescript enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" } let dir: Direction = Direction.Up; console.log(dir); // "UP" ``` **Why enums?** Type-safe alternative to string constants with autocomplete support. ## Numeric Enums Default enums are numeric with auto-increment: ```typescript enum Status { Pending, // 0 Approved, // 1 Rejected // 2 } let s: Status = Status.Approved; console.log(Status[1]); // "Approved" (reverse mapping) ``` **Tip:** Use explicit values for clarity: `Status = { Pending: 0, ... }`. ## String Enums String enums are more readable and don't have reverse mapping: ```typescript enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" } ``` **Remember:** Prefer string enums — they're self-documenting in logs and errors. ## Const Enums Const enums are inlined at compile time for performance: ```typescript const enum Direction { Up = "UP", Down = "DOWN" } let dir = Direction.Up; // Compiled to: let dir = "UP"; ``` **Tip:** Use const enums in library code to reduce bundle size. ## Enums with Functions ```typescript enum Role { Admin = "admin", Editor = "editor", Viewer = "viewer" } function canEdit(role: Role): boolean { return role === Role.Admin || role === Role.Editor; } canEdit(Role.Admin); // true canEdit(Role.Viewer); // false ``` ## Iterating Enums ```typescript enum Direction { Up = "UP", Down = "DOWN" } // Get all values let values = Object.values(Direction); // ["UP", "DOWN"] ``` ## Best Practices - Prefer string enums over numeric - Use const enums for performance in libraries - Keep enums focused — one concept per enum - Consider literal unions as a simpler alternative ## Common Mistakes - Numeric enums without explicit values are hard to debug - Mixing numeric and string values in one enum - Overusing enums when literal unions work fine - Not handling all enum cases in switch statements
No changes yet
Reset to original
Submit suggestion
cancel