Enum inheritance

Topics: Language Specification
Jun 19, 2013 at 6:39 PM
Suppose I define an enum A with a whole bunch of names/values. I then want to define another enum B with all the same entries as A but with some additional ones as well. It would be tedious and error-prone to have to copy all the entries from A. And also I'd lose some important semantic information, that B 'inherits' from A. So has anyone on the TypeScript team thought about applying inheritance to enums? And without it are there any elegant ways of achieving the same effect in TypeScript as currently defined?
Jun 20, 2013 at 3:38 AM
How do you achieve this effect with other languages you've used? I'm unfamiliar with others that do enum inheritance. As enums have values associated with them you'd really be doing something more like a mixin, in which case if that were well supported you could just use interfaces for this purpose (ie A is an interface with properties with a default value, and you mixin A to B which defines additional properties and values).
Jun 20, 2013 at 9:12 AM
Mainstream languages don't support this, but most don't support extensible enums either (although I've used them in the past in various domain-specific languages I've developed). That's one of the interesting aspects of TypeScript IMO. Normally you start with a language/type system, and then begin writing the programs. In the case of TypeScript we start with the relative anarchy of JavaScript, and then try to impose some sanity/order on as much of it as we can by developing an interesting and powerful type system. That's obviously challenging given some of the JavaScript programs out there :-) But TypeScript has the advantage that it doesn't have to support the sorts of type safety guarantees that some statically-typed languages require. I'd come across examples where the JavaScript code would map naturally to TypeScript enums, but where there would be a lot of duplications. You are right that we could ignore enums all together in such cases, just using interfaces etc. But that loses a lot of semantic information that's implied in an enum, loses potentially a lot of compile-time checking potential etc. Which was what got me thinking about why we don't allow enum inheritance in languages. Maybe there's a killer use-case that shows why it's not a good idea, which was why I thought it was worth raising as a question.