TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Extending string-based enums

Open nomaed opened this issue 9 years ago • 88 comments

Before string based enums, many would fall back to objects. Using objects also allows extending of types. For example:

const BasicEvents = {
    Start: "Start",
    Finish: "Finish"
};

const AdvEvents = {
    ...BasicEvents,
    Pause: "Pause",
    Resume: "Resume"
};

When switching over to string enums, it"s impossible to achieve this without re-defining the enum.

I would be very useful to be able to do something like this:

enum BasicEvents {
    Start = "Start",
    Finish = "Finish"
};

// extend enum using "extends" keyword
enum AdvEvents extends BasicEvents {
    Pause = "Pause",
    Resume = "Resume"
};

Considering that the produced enums are objects, this won"t be too horrible either:

// extend enum using spread
enum AdvEvents {
    ...BasicEvents,
    Pause = "Pause",
    Resume = "Resume"
};

nomaed avatar Aug 03 '17 16:08 nomaed

@m93a Ah, so you mean that extends here in effect has more of a copying semantics (of the enum values from A into B)? Then, yes, the switches come out OK.

However, there is some expectation in there that still seems broken to me. As a way to try and nail it down: with classes, extends does not convey copying semantics — fields and methods do not get copied into the extending subclass; instead, they are just made available via the prototype chain. There is only ever one field or method, in the superclass.

Because of this, if class B extends A, we are guaranteed that B is assignable to A, and so for example let a: A = new B(); would be perfectly fine.

But with enums and extends, we wouldn't be able to do let a: A = B.b;, because there is no such corresponding guarantee. Which is what feels odd to me; extends here conveys a certain set of assumptions about what can be done, and they are not met with enums.

masak avatar Mar 13 '19 09:03 masak

Then just calling it expands or clones? 🤷‍♂️ From a users perspective it just feels odd that something that basic is not straightforward to achieve.

wottpal avatar Mar 13 '19 12:03 wottpal

If the reasonable semantics requires a whole new keyword (without much of prior art in other languages), why not instead re-use the spread syntax (...) as suggested in OP and this comment?

masak avatar Mar 13 '19 13:03 masak

+1 I hope this will be added to the default enumeration feature. :)

ninezero90hy avatar Mar 15 '19 15:03 ninezero90hy

Does anyone know any elegant solutions??? 🧐

ninezero90hy avatar Mar 15 '19 15:03 ninezero90hy

If the reasonable semantics requires a whole new keyword (without much of prior art in other languages), why not instead re-use the spread syntax (...) as suggested in OP and this comment?

Yes, after thinking about it a bit more I think this solution would be good.

wottpal avatar Mar 19 '19 11:03 wottpal

After reading this whole issue thread, it seems that there is a broad agreement that re-using the spread operator solves the issue, and addresses all of the concerns people have raised about making the syntax confusing/unintuitive.

// extend enum using spread
enum AdvancedEvents {
    ...BasicEvents,
    Pause = "Pause",
    Resume = "Resume"
};

Does this issue really still need the "Awaiting More Feedback" label at this point, @RyanCavanaugh ?

masonmark avatar Apr 12 '19 07:04 masonmark

The feature wanted +1

nighca avatar May 07 '19 09:05 nighca

Do we have any news on this issue ? It feels really useful to have the spreading operator implemented for enums.

arthur-caillaud avatar Jul 29 '19 16:07 arthur-caillaud

Especially for use cases that involve metaprogramming the ability to alias and extend enums is somewhere between a must-have and a nice-to-have. There's no way currently to take one enum and export it in another name - unless you resort to one of the workarounds mentioned above.

nadeesha avatar Aug 01 '19 01:08 nadeesha

@m93a Ah, so you mean that extends here in effect has more of a copying semantics (of the enum values from A into B)? Then, yes, the switches come out OK.

However, there is some expectation in there that still seems broken to me. As a way to try and nail it down: with classes, extends does not convey copying semantics — fields and methods do not get copied into the extending subclass; instead, they are just made available via the prototype chain. There is only ever one field or method, in the superclass.

Because of this, if class B extends A, we are guaranteed that B is assignable to A, and so for example let a: A = new B(); would be perfectly fine.

But with enums and extends, we wouldn't be able to do let a: A = B.b;, because there is no such corresponding guarantee. Which is what feels odd to me; extends here conveys a certain set of assumptions about what can be done, and they are not met with enums.

@masak I think you're close to correct but you made one small assumption that is incorrect. B is assignable to A in the event of enum B extends A as "assignable" means that all values provided by A are available in B. When you said that let a: A = B.b you are assuming that values in B must be available in A, which is not the same as the values being assignable to A. let a: A = B.a IS correct because B is assignable to A.

This is evident using classes like in the following example:

class A {
 a() {}
}

class B extends A {
 b() {}
}

let a: A = new B();

a.a();  // valid
a.b();  // invalid via type system since `a` is typed as `A`

TypeScript Playground Link

invalid access

Long story short, I believe extends IS the correct terminology as that is exactly what is being done. In the enum B extends A example you can ALWAYS expect a B enum to contain all the possible values of the A enum, because B is a "subclass" (subenum? maybe there is a better word for this) of A and thus assignable to A.

So I don't think we need a new keyword, I think we should use extends AND I think this should be natively a part of TypeScript :D

julian-sf avatar Sep 06 '19 18:09 julian-sf

@julian-sf I think I agree with every thing you wrote...

...but... :slightly_smiling_face:

as I problematized here, what about this situation?

// example from OP
enum BasicEvents {
    Start = "Start",
    Finish = "Finish"
};

// extend enum using "extends" keyword
enum AdvEvents extends BasicEvents {
    Pause = "Pause",
    Resume = "Resume"
};

Given that Pause is an instance of AdvEvents and AdvEvents extends BasicEvents, would you also expect Pause to be an instance of BasicEvents? (Because that seems to follow from how the instance/inheritance relations usually interact.)

On the other hand, the core value proposition of enums (IMHO) is that they are closed/"final" (as in, non-extensible) so that something like a switch statement can assume totality. (And so AdvEvents being able to extend what it means to be a BasicEvent violates some kind of Least Surprise for enums.)

I don't think that you can more than two of the following three properties:

  • Enums being closed/final/predictably total
  • An extends relation between two enum declarations
  • The (reasonable) assumption that if b is an instance of B and B extends A, then b is an instance of A

masak avatar Sep 06 '19 19:09 masak

@masak I understand and agree with the closed principal of enums (at runtime). But compile time extension would not violate the closed principle at runtime, as they would all be defined and constructed by the compiler.

The (reasonable) assumption that if b is an instance of B and B extends A, then b is an instance of A

I think this reasoning is kind of misleading as the instance/class dichotomy is not really assignable to enum. Enums are not classes and they do not have instances. I do think however, that they can be extensible, if done properly. Think of enums more like sets. In this example, B is a superset of A. Therefore it is reasonable to assume that any value in A is present in B, but that only SOME values of B will be present in A.

I understand where the concern comes from...though. And I'm not sure what to do about that. A good example of an issue with enum extension:

const enum A { a = 'a' }
const enum B extends A { b = 'b' }

const foo = (a: A) => console.log(a);
const bar = (b: B) => foo(b);

bar(B.a); // 'a'
bar(B.b); // uh-oh, b doesn't exist on A, so foo would get unexpected behavior

// HOWEVER, this would work just fine...

const baz = (a: A) => bar(a);

baz(A.a); // 'a'
baz(B.a); // 'a'
baz(B.b); // compiler error as expected...

In this case, enums behave quite differently than classes. If these were classes, you would expect to be able to cast B to A quite easily, but that clearly won't work here. I don't necessarily think this is BAD, I think it should just be accounted for. IE, you can't scope an enum type upwards in its inheritance tree like a class. This could be accounted for with a compiler error along the lines of "cannot assign superset enum B to A, as not all values of B are present in A".

julian-sf avatar Sep 10 '19 19:09 julian-sf

@julian-sf

I think this reasoning is kind of misleading as the instance/class dichotomy is not really assignable to enum. Enums are not classes and they do not have instances.

You're absolutely right, on the face of it.

  • Seen as an independent language construct, an enumeration has members, not instances. The term "member" is used both by the Handbook and the Language Specification. (C# and Python similarly use the term "member". Java uses "enum constant", because "member" has an overloaded meaning in Java.)
  • Seen from a compiled-code perspective, an enum has properties, mapping both ways — names-to-values and values-to-names. Again, not instances.

Thinking about this, I realize that I'm colored a little bit by Java's take on enums. In Java, enum values are literally instances of their enum type. Implementation-wise, an enum is a class extending the Enum class. (You're not allowed to do it manually, you have to go through the enum keyword, but that's what happens under the hood.) The nice thing about this is that enums get all the conveniences classes do: they can have fields, constructors, methods... In this appproach, enum members are instances. (The JLS says as much.)

Note that I'm not proposing any changes to TypeScript enum semantics. In particular, I'm not saying TypeScript should change to using Java's model for enums. I am saying that it's instructive/insightful to overlay a class/instance "understanding" on top of enums/enum members. Not "an enum is a class" or "an enum member is an instance"... but there are similarities that carry over.

What similarities? First and foremost, type membership.

enum Foo { A, B, C }
enum Bar { X, Y, Z }

let foo: Foo = Foo.C;
foo = Bar.Z;

The last line doesn't typecheck, because Bar.Z is not a Foo. Again, this is not actually classes and instances, but it can be understood using the same model, as if Foo and Bar were classes and the six members were their respective instances.

(We'll ignore for the purposes of this argument the fact that let foo: Foo = 2; is also semantically legal, and that in general, number values are assignable to variables of enum type.)

Enums have the additional property that they are closed — sorry, I don't know a better term for this — once you define them, you cannot extend them. Specifically, the members listed inside of the enum declaration are the only things that typematch against the enum type. ("Closed" as in "closed-world hypothesis".) This is a great property because you can verify with total certainty that all the cases in a switch statement on your enum have been covered.

With extends on enums, this property goes out the window.

You write,

I understand and agree with the closed principal of enums (at runtime). But compile time extension would not violate the closed principle at runtime, as they would all be defined and constructed by the compiler.

I don't think that's true, because it assumes that any code that extends your enum is in your project. But a third-party module can extend your enum, and suddenly there are new enum members that are also assignable to your enum, outside of the control of code that you compile. Essentially, enums would no longer be closed, not even at compile-time.

masak avatar Nov 05 '19 02:11 masak

I still feel I'm somewhat clumsy in expressing exactly what I mean, but I believe it's important: extends on enum would break one of the most precious features of enums, the fact that they're closed. Please count how many languages absolutely forbid extending/subclassing an enum, for this very reason.

masak avatar Nov 05 '19 02:11 masak

I thought about workarounds a little more, and working off of #17592 (comment) , you can do a little better by also defining Events in the value space:

enum BasicEvents {
  Start = 'Start',
  Finish = 'Finish'
}
enum AdvEvents {
  Pause = 'Pause',
  Resume = 'Resume'
}
type Events = BasicEvents | AdvEvents;
const Events = {...BasicEvents, ...AdvEvents};

let e: Events = Events.Pause;

From my testing, looks like Events.Start is correctly interpreted as BasicEvents.Start in the type system, so exhaustiveness checking and discriminated union refinement seem to work fine. The main thing missing is that you can't use Events.Pause as a type literal; you need AdvEvents.Pause. You can use typeof Events.Pause and it resolves to AdvEvents.Pause, though people on my team have been confused by that sort of pattern and I think in practice I'd encourage AdvEvents.Pause when using it as a type.

(This is for the case when you want the enum types to be assignable between each other rather than isolated enums. From my experience, it's most common to want them to be assignable.)

I think this is the neatest solution at hand, right now.

Thank you @alangpierce :+1:

MajidJafari avatar Dec 03 '19 08:12 MajidJafari

any update on this?

sdwvit avatar May 26 '20 19:05 sdwvit

@sdwvit I'm not one of the core people, but from my vantage point, the following syntax proposal (from OP, but re-suggested twice after that) would make everyone happy, without any known issues:

// extend enum using spread
enum AdvEvents {
    ...BasicEvents,
    Pause = "Pause",
    Resume = "Resume"
};

It would make me happy, because it would mean implementing this seemingly useful "duplicate all the members in this other enum" feature without using extends, which I consider to be problematic for reasons I've stated. The ... syntax avoids these issues by copying, not extending.

The issue is still marked as "Awaiting More Feedback", and I respect the core members' right to keep it in that category for as long as they feel is necessary. But also, there's nothing to stop anyone from implementing the above and submitting it as a PR.

masak avatar May 27 '20 02:05 masak

@masak thank you for response. I now have to go through all the discussion history. Will get back to you after :)

sdwvit avatar May 27 '20 03:05 sdwvit

I would absolutely love to see this happen and would absolutely love to attempt to implement this myself. However we still need to define behaviors for all enums. This all works well for string-based enums, but what about vanilla numeric enums. How does extending/copying work here?

  • I assume we will only want to allow extending an enum with a "same type" enum (numeric extends numeric, string extends string). Heterogeneous enums are technically supported so I suppose we should keep that support.

  • Should we allow extending from multiple enums? Should they all have mutually exclusive values? Or will we allow overlapping values? Priority based on lexical order?

  • Can the extending enums override values of the extended enums?

  • Must the extended enums appear that the start of the list of values or can it be in any order? I assume later defined values have higher priority?

  • I assume implicit numeric values will continue 1 after the max value of the extended numeric enums.

  • Special considerations for bit-masks?

etc. etc.

JeffreyMercado avatar Jun 11 '20 01:06 JeffreyMercado