As of now Enum
have their peculiarities in Typescript; they can behave hmm... How should I put it? Inconsistenly. If you still love Enums then, let me suggest some EsLint rules for writing better Enum
Table of Contents
Prerequisites
- EsLint: New to ESLint? It helps you write better JavaScript and TypeScript. https://typescript-eslint.io/
Enums peculiarities
I am going to walk you through a few peculiarities I’ve come across while building components using declarative rendering.
Let me show you with examples
Enums with string or number values
Enums behave different when its created with string values versus numbers.
With string values
enum TransferStatus {
Pending = 'pending',
Completed = 'completed',
Failed = 'failed',
}
console.log(Object.keys(TransferStatus))
// Output : ["Pending", "Completed", "Failed"]
With number values
enum TransferStatus {
Pending,
Completed,
Failed,
}
console.log(Object.keys(TransferStatus))
// Output : ["0", "1", "2", "Pending", "Completed", "Failed"]
// 🤯 Wow, I got all keys and all values
console.log(Object.values(TransferStatus))
// Output: ["Pending", "Completed", "Failed", 0, 1, 2]
// 🤡 All values and keys
Enums declared explicitly versus implicitly
Enums dont behave the same way when they are declared explicitly versus implicitly. With numbers, values may loose order when refactoring
With explicit values
enum GameDifficulty {
Easy = 0,
Normal = 1,
Hard = 2,
}
// If ordered alphabetically
enum GameDifficulty {
Easy = 0,
Hard = 2,
Normal = 1,
}
// All good here with order
With implicit values
enum GameDifficulty {
Easy,
Normal,
Hard,
}
// If ordered alphabetically
enum GameDifficulty {
Easy,
Hard,
Normal,
}
// value of Hard changed from 2 to 1
// 🤯 You would have to apply changes everywhere in your code
Helpful ESLint Rules for Enums!
If you still love Enums, then I'd suggest using some EsLint rules to enforce consistency and make code more predictable for you and your team members
- Initialize Enum values explicitly for clarity and consistency
'@typescript-eslint/prefer-enum-initializers': 'error'
- Ensure all enum values are unique.
'@typescript-eslint/no-duplicate-enum-values': 'error'
- Use enums with string values only This is the one I like. Consitency all the way! 💞
@typescript-eslint/no-magic-numbers': [
'error',
{
'ignoreEnums': false
}
]
Summary
In this post, I address common inconcistencies with Enum when building dynamic declarative components. I also show with some examples that you met when building components dinamycally.
It also shares some EsLint rules to safeguard you against the peculiarities of Enum.