-
Notifications
You must be signed in to change notification settings - Fork 9
Description
I feel like, as a JavaScript community, we keep asking for enums because it's what every other language has, and we run into lots of problems that would be solved by enums. But I'm not sure we really want them in the language. The primary problems enums are intended to solve we've learned how to solve in other ways. Dedicated enum syntax is, in many ways, a clunkier way to solve the problem we already know how to solve.
I'm going to start by speaking from a TypeScript perspective.
TypeScript already has excellent enum support, and no, I'm not talking about their enum syntax. I'm talking about union types.
type TrafficLightState = 'RED' | 'YELLOW' | 'GREEN';
function getState(): TrafficLightState { ... }
console.log('Stop?', getState() === 'RED');Now lets throw in the proposed enum syntax.
enum TrafficLightState {
RED = 'RED',
YELLOW = 'YELLOW',
GREEN = 'GREEN',
}
function getState(): TrafficLightState { ... }
console.log('Stop?', getState() === 'RED');
// Or if you really wanted to, but there's no reason real to do it
console.log('Stop?', getState() === TrafficLightState.RED);I know it's early days for syntax discussion, but if the currently proposed enum syntax stays the same, then personally I wouldn't use it in my own code - unions are much more terse. Technically the enum syntax has the advantage that it's a runtime value that you can iterate over, but in practice it's extremely rare for me to need that capability.
Speaking from a non-TypeScript perspective, it's common to use objects in place of enums as a way to self-document the available enum values.
const trafficLightState = {
RED: 'RED',
YELLOW: 'YELLOW',
GREEN: 'GREEN',
};If I use enum syntax, then I get the benefit of the object automatically being non-extensible, which is cool, but also, meh. It's not like preventing extension on these objects is all that important when I'm not doing the same thing on anything else in my codebase. Or, maybe I am freezing/preventing-extension all over the place, in which case it's not that much trouble to do it on the enum-like objects as well.
Conclusion
Perhaps we don't need to be like other languages. We don't really need enum types. What we already have seems to be working really well, so well in fact that dedicated enum syntax actually feels inferior to use.