What if a tiny typo in your code could silently break your program? String enums stop that from happening.
Why String enums in Typescript? - Purpose & Use Cases
Imagine you are writing a program where you need to handle different user roles like 'admin', 'editor', and 'viewer'. You write these roles as plain strings everywhere in your code.
At first, it seems easy, but as your program grows, you have to type these strings many times in different places.
Typing the same strings repeatedly is slow and easy to mess up. A small typo like 'admn' instead of 'admin' can cause bugs that are hard to find.
Also, if you want to change a role name, you have to search and update every place manually, which is tiring and error-prone.
String enums let you define all your string values in one place with clear names. Then, you use these names everywhere in your code.
This way, you avoid typos because the computer checks your code. If you want to change a string, you do it once in the enum, and it updates everywhere.
if (role === 'admin') { // do admin stuff } if (role === 'admn') { // typo causes bug }
enum UserRole {
Admin = 'admin',
Editor = 'editor',
Viewer = 'viewer'
}
if (role === UserRole.Admin) {
// do admin stuff
}String enums make your code safer, easier to read, and simpler to maintain by grouping related string values under clear names.
Think of a traffic light system where states like 'red', 'yellow', and 'green' are used. Using string enums ensures you only use these exact states everywhere, preventing mistakes like 'gren' or 'redd'.
Typing strings repeatedly leads to errors and slow updates.
String enums group related strings with clear names in one place.
This reduces bugs and makes code easier to maintain.
Practice
string enums in TypeScript?Solution
Step 1: Understand string enums purpose
String enums group related string values under named constants to improve code clarity and safety.Step 2: Compare options
Only They group related string constants under named values for clarity. correctly describes this benefit. Numeric auto-assignment and mixing types are not features of string enums.Final Answer:
They group related string constants under named values for clarity. -> Option AQuick Check:
String enums improve clarity = A [OK]
- Confusing string enums with numeric enums
- Thinking enum members can be implicit strings
- Assuming enums mix string and number types
Solution
Step 1: Review string enum syntax
String enums require explicit string values assigned to each member using= 'value'inside anenumblock.Step 2: Check each option
enum Colors { Red = 'RED', Green = 'GREEN', Blue = 'BLUE' } correctly usesenum 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.Final Answer:
enum Colors { Red = 'RED', Green = 'GREEN', Blue = 'BLUE' } -> Option CQuick Check:
String enum syntax = D [OK]
- Omitting string values for enum members
- Using object literal syntax instead of enum
- Missing quotes around string values
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
console.log(Direction.Left);Solution
Step 1: Understand enum member values
Each member in the string enum has an explicit string value, e.g.,Left = "LEFT".Step 2: Check console.log output
LoggingDirection.Leftprints the string value assigned, which is "LEFT".Final Answer:
"LEFT" -> Option BQuick Check:
Enum member value = "LEFT" [OK]
- Expecting member name instead of value
- Confusing string enums with numeric enums
- Assuming enum members print numeric indexes
enum Status {
Active = ACTIVE,
Inactive = "INACTIVE"
}Solution
Step 1: Check string enum member values
String enum members must have explicit string values in quotes, e.g.,"ACTIVE".Step 2: Identify error in Active member
TheActivemember usesACTIVEwithout quotes, causing a reference error.Final Answer:
Missing quotes around ACTIVE in Active member -> Option DQuick Check:
String values need quotes = A [OK]
- Forgetting quotes around string values
- Mixing string and numeric enum members
- Assuming enum names have restrictions
enum Role {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
}Which code snippet correctly checks if a variable
r is a valid Role value?Solution
Step 1: Understand enum value checking
To check ifris a valid enum value, compare it against the enum's values, not keys.Step 2: Evaluate each option
if (Object.values(Role).includes(r)) { /* valid */ } usesObject.values(Role).includes(r), correctly checking ifrmatches 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.Final Answer:
if (Object.values(Role).includes(r)) { /* valid */ } -> Option AQuick Check:
Check enum values with Object.values() = B [OK]
- Checking keys instead of values
- Comparing value directly to enum object
- Using enum indexing with string values
Ready to prove it?
Pass the test and this pattern moves unknown
