#Magical enums in ES6 My brain exploded with creativity today with this nefarious trick to make an enum by manipulating the syntax in ES6. The browser vendors will probably find this and block this from shipping, but it will still work with a transpiler (webpack + 6to5). To understand this you will need to know ES6 Proxies, ES6 modules, and Symbols.
your-code.js
import { blue, red, orange } from 'magic-enum';
var color = blue;
switch (color) {
case blue:
console.log('color is blue!!');
break;
case red:
console.log('color is red!!');
break;
case orange:
console.log('color is orange!');
break;
}
The small amount of code that makes it happen...
magic-enum.js
var magic = {};
export default new Proxy(magic, {
get(target, property) {
return Symbol(property);
}
})
Of course this means that your enum cannot have initializers (i.e. { blue=1, red, green }
).