Greetings,
I would like to propose an addition of the 'enum' keyword. Most, if not all of you already know the basic use of enums. But let me elaborate why it would be useful in case of ECMAScript.
There are many cases which I stumbled upon where ECMAScript developers define const objects as basic "enums". There is usually a need to stay consistent with some predefined values descibing a behaviour or entity trait. For this example, I'll use a simple accountType enum (basic, premium, VIP).
Currently, the best way to define this in code would be
const accountType = {
basic: 'basic',
premium: 'premium',
vip: 'vip',
};
It would also be ideal to then freeze this object to avoid situations of silent property redefinitions or additions. This works, but I consider this to be too verbose and a great candidate for simplification and standardization.
With 'enum' keyword available, we could simply define this as:
// definition
enum AccountType {
basic,
premium,
vip,
}
// usage
let account = {
username: 'johndoe',
email: 'johndoe@mail.com',
type: AccountType.basic,
};
Enums should be completely frozen and impossible to modify after the definition, by implementation.
It should be decided what the enum would be serialized into. I would definitely support the string-by-default implementation, where AccountType.basic
would evaluate as basic
. integer-based enums are more ambiguous when persisting their values so string representation would probably be a way to go.
This way, there would be no more questions regarding "what is the best way to define enums in javascript" or discussions on stackoverflow about freezing an object, avoiding issues with serialization etc.
I would not endorse overcomplication of this topic. This means that I don't ask for heterogenous enums, integer-based enums with possibility of defining start of sequence etc. (I am pulling these examples from TypeScript implementation). For now, at least, I consider the above-described implementation as "more than good enough" for majority of use cases.