This is a very early stage 0 exploration to add enums to Javascript, as a syntatic simplication over a common pattern to define enumerations.
Enums come up often in code bases (TODO: try to estimate a number) and it is easy to get it incorrectly. Specifically, it is easy to forget:
- to
Object.freeze
the object - to declare it as a
const
which avoids having the symbol redefined
With this in mind, we propose a nem keyword to javascript, say enum
which de-sugars to the following:
// if you write this ...
enum Foo {
BAR: 1,
HELLO "hello",
WORLD: false
}
// ... it gets de-sugared to:
const Foo = Objec.freeze({
BAR: 1,
HELLO: "hello",
WORLD: false
});
// TODO(goto): should we use Symbols here for extra type safety?
Prior art
Lots of good references and proposals in this thread. Here are a few:
https://github.com/stevekinney/ecmascript-enumerations
https://esdiscuss.org/topic/propose-simpler-string-constant#content-14
https://en.wikipedia.org/wiki/Enumerated_type
https://github.com/rwaldron/proposal-enum-definitions
https://docs.python.org/3/library/enum.html
https://esdiscuss.org/topic/enums
http://2ality.com/2011/10/enums.html