Concept Flow - String enums
Define enum with string values
Use enum member in code
Access string value of enum member
Use string value for comparison or output
End
This flow shows how a string enum is defined, used, and accessed in TypeScript.
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
console.log(Direction.Up);| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define enum Direction with string values | Direction.Up = "UP", Direction.Down = "DOWN", Direction.Left = "LEFT", Direction.Right = "RIGHT" | Enum Direction created with string values |
| 2 | Access Direction.Up | Direction.Up | "UP" |
| 3 | Print Direction.Up | console.log(Direction.Up) | Output: UP |
| 4 | End of code execution | - | - |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| Direction.Up | undefined | "UP" | "UP" | "UP" |
| Direction.Down | undefined | "DOWN" | "DOWN" | "DOWN" |
| Direction.Left | undefined | "LEFT" | "LEFT" | "LEFT" |
| Direction.Right | undefined | "RIGHT" | "RIGHT" | "RIGHT" |
String enums in TypeScript assign explicit string values to enum members.
Syntax: enum Name { Member = "string" }
Use enum members to get their string values.
Useful for readable constants instead of numbers.
Compare enum members directly to strings.string enums in TypeScript?= 'value' inside an enum block.enum Colors { Red = 'RED', ... }. enum Colors { Red, Green, Blue } lacks string assignments. enum Colors = { Red: 'RED', Green: 'GREEN', Blue: 'BLUE' } uses invalid syntax with = outside enum. const enum Colors { Red = RED, Green = GREEN, Blue = BLUE } misses quotes around string values.enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
console.log(Direction.Left);Left = "LEFT".Direction.Left prints the string value assigned, which is "LEFT".enum Status {
Active = ACTIVE,
Inactive = "INACTIVE"
}"ACTIVE".Active member uses ACTIVE without quotes, causing a reference error.enum Role {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
}r is a valid Role value?r is a valid enum value, compare it against the enum's values, not keys.Object.values(Role).includes(r), correctly checking if r matches any enum string value. if (r in Role) { /* valid */ } checks keys, not values. if (r === Role) { /* valid */ } compares a string to the enum object itself. if (Role[r]) { /* valid */ } tries to index enum with string value, which fails.Pass the test and this pattern moves unknown