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

@JeffreyMercado These are good questions, and appropriate for one who hopes to attempt an implementation. :smile:

Below are my answers, guided by a "conservative" design approach (as in "let's make design decisions that disallow the cases we're not sure about, rather than making choices now that are hard to change later while staying backwards compatible").

  • I assume we will only want to allow extending an enum with a "same type" enum (numeric extends numeric, string extends string)

I assume so too. The resulting enum of mixed type doesn't seem super-useful.

  • 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?

Since it's copying semantics we're talking about, duplicating multiple enums seems "more ok" than Multiple Inheritance à la C++. I don't immediately see a problem with it, especially if we keep building on the analogy of object spread: let newEnum = { ...enumA, ...enumB };

Should all the members have mutually exclusive values? The conservative thing would be to say "yes". Again, the analogy of object spread provides us with an alternative semantics: last one wins.

I can't think of any use cases where I would appreciate being able to override enum values. But that might just be a lack of imagination on my part. The conservative approach of disallowing collisions has the pleasing properties that it's easy to explain/internalize, and at least in theory it might expose real design errors (in fresh code, or code that's being maintained).

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

I think the answer, and the reasoning, are much the same in this case as in the previous case.

  • 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 was going to say first that this only matters if we go with the "last one wins" semantics of overriding.

But on second thought, both under "no collisions" and "last one wins", I find it weird to even want to put enum member declarations before enum spreads in the list. Like, what intent is being communicated by doing so? The spreads are a little like "imports", and these conventionally go at the top.

I don't necessarily want to forbid putting enum spreads after enum member declarations (although I think I would be fine with it being disallowed in the grammar). If it ends up being allowed, it's definitely something that linters and community convention could point out as avoidable. There's just no compelling reason to do so.

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

Maybe the conservative thing to do is to require an explicit value for the first member after a spread.

  • Special considerations for bit-masks?

I think that would be covered by the above rule.

masak avatar Jun 11 '20 01:06 masak

I was able to do something reasonable by combining enums, interfaces, and immutable objects.

export enum Unit {
    SECONDS,
    MINUTES,
    HOURS,
    DAYS,
    WEEKS,
    MONTHS,
    YEARS,
    DECADES,
    CENTURIES,
    MILLENNIA
}

interface Labels {
    SINGULAR: Record<Unit, string>
    PLURAL: Record<Unit, string>
    LAST: string;
    DELIM: string;
    NOW: string;
}

export const EnglishLabels: Labels = {
    SINGULAR: {
        [Unit.SECONDS]: ' second',
        [Unit.MINUTES]: ' minute',
        [Unit.HOURS]: ' hour',
        [Unit.DAYS]: ' day',
        [Unit.WEEKS]: ' week',
        [Unit.MONTHS]: ' month',
        [Unit.YEARS]: ' year',
        [Unit.DECADES]: ' decade',
        [Unit.CENTURIES]: ' century',
        [Unit.MILLENNIA]: ' millennium'
    },
    PLURAL: {
        [Unit.SECONDS]: ' seconds',
        [Unit.MINUTES]: ' minutes',
        [Unit.HOURS]: ' hours',
        [Unit.DAYS]: ' days',
        [Unit.WEEKS]: ' weeks',
        [Unit.MONTHS]: ' months',
        [Unit.YEARS]: ' years',
        [Unit.DECADES]: ' decades',
        [Unit.CENTURIES]: ' centuries',
        [Unit.MILLENNIA]: ' millennia'
    },
    LAST: ' and ',
    DELIM: ', ',
    NOW: ''
}

illeatmyhat avatar Jun 14 '20 03:06 illeatmyhat

@illeatmyhat That's a nice use of enums, but... I fail to see how it counts as extending an existing enum. What you're doing is using the enum.

(Also, unlike with enums and switch statements, it seems that in your example you have no totality checking; someone who added an enum member later might easily forgot to add a corresponding key in the SINGULAR and PLURAL record in all the instances of Label.)

masak avatar Jun 14 '20 09:06 masak

@masak

someone who added an enum member later might easily forgot to add a corresponding key in the SINGULAR and PLURAL record in all the instances of Label.)

At least in my environment, it throws an error when an enum member is missing from either SINGULAR or PLURAL. The Record type does its job, I guess.

While the documentation for TS is good, I feel that there aren't many examples of how to combine many features together in a nontrivial way. enum inheritance was the first thing I looked up when I tried to solve internationalization problems, leading to this thread. The approach turned out to be wrong anyways, which is why I wrote this post.

illeatmyhat avatar Jun 14 '20 10:06 illeatmyhat

@illeatmyhat

At least in my environment, it throws an error when an enum member is missing from either SINGULAR or PLURAL. The Record type does its job, I guess.

Oh! TIL. And yes, that does make it a lot more interesting. I see what you mean about initially reaching for enum inheritance and eventually landing on your pattern. That might not even be an isolated thing; "X/Y problems" are a real thing. More people might start with the thought "I want to extend MyEnum", but end up using Record<MyEnum, string> like you did.

masak avatar Jun 14 '20 12:06 masak

Reply to @masak:

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

You write,

@julian-sf: 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.

The more I think about this, you're completely right. Enums should be closed. I really like the idea of "composing" enums as I think this is really the heart of the matter we want here 🥳.

I think this notation summarizes the concept of "stitching together" two separate enums quite elegantly:

enum ComposedEnum = { ...EnumA, ...EnumB }

So consider that my resignation on using the term extends 😆


Comments on @masak's answers to @JeffreyMercado's questions:

  • 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.

I assume so too. The resulting enum of mixed type doesn't seem super-useful.

Whilst I agree that it's not useful, we SHOULD probably keep heterogeneous support for enums here. I think a linter warning would be useful here, but I don't think TS should get in the way of that. I can think of a contrived use case which is, I'm building an enum for interactions with a very poorly designed API that takes flags that are a mix of numbers and strings. Contrived, I know, but since it's allowed elsewhere, I don't think we should disallow it here.

Maybe just strong encouragement not to?

  • 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?

Since it's copying semantics we're talking about, duplicating multiple enums seems "more ok" than Multiple Inheritance à la C++. I don't immediately see a problem with it, especially if we keep building on the analogy of object spread: let newEnum = { ...enumA, ...enumB };

100% agree

  • Should all the members have mutually exclusive values?

The conservative thing would be to say "yes". Again, the analogy of object spread provides us with an alternative semantics: last one wins.

I'm torn here. While I agree it's "best practice" to enforce mutual exclusivity of values, is it correct? It is directly contradictory to commonly-known spread semantics. One the one hand, I like the idea of enforcing mutually exclusive values, on the other hand, it breaks a lot of assumptions about how spread semantics should work. Are there any downsides to following normal spreading rules with "last one wins"? It seems like it's easier on implementation (as the underlying object is just a map anyway). But it also seems to align with common expectations. I'm leaning towards being less surprising.

There may also be good examples for wanting to override a value (although I have no idea what those would be).

But on second thought, both under "no collisions" and "last one wins", I find it weird to even want to put enum member declarations before enum spreads in the list. Like, what intent is being communicated by doing so? The spreads are a little like "imports", and these conventionally go at the top.

Well that depends, if we are following spread semantics, then it shouldn't matter what the order is. Honestly, even if we are enforcing mutually exclusive values the order wouldn't really matter, right? A collision would be an error at that point, regardless of order.

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

Maybe the conservative thing to do is to require an explicit value for the first member after a spread.

I agree. If you spread an enum, TS should just enforce explicit values for additional members.

julian-sf avatar Jun 18 '20 17:06 julian-sf

@julian-sf

So consider that my resignation on using the term extends 😆

:+1: The Society for the Preservation of Sum Types cheers from the sidelines.

But on second thought, both under "no collisions" and "last one wins", I find it weird to even want to put enum member declarations before enum spreads in the list. Like, what intent is being communicated by doing so? The spreads are a little like "imports", and these conventionally go at the top.

Well that depends, if we are following spread semantics, then it shouldn't matter what the order is. Honestly, even if we are enforcing mutually exclusive values the order wouldn't really matter, right? A collision would be an error at that point, regardless of order.

I'm saying "there's no good reason to place spreads after normal member declarations"; you're saying "under the appropriate restrictions, placing them before or after makes no difference". Both of these things can be true at the same time.

The main difference in outcome seems to fall on a spectrum of allowing or disallowing spreads before normal members. It could be syntactically disallowed; it could produce a linter warning; or it could be completely fine in all regards. If the order makes no semantic difference, then it comes down to making the enum spread feature follow the principle of Least Surprise, easy to use, and easy to teach/explain.

masak avatar Jun 19 '20 03:06 masak

Using the spread operator falls in the wider use of shallow copy throughout JS and TypeScript. It's certainly the more widely used and easier to understand method than using extends, which implies a direct relationship. Creating an enum through composition would be the easier solution to consume.

Some of the work around suggestions, while valid and usable, add a lot more boilerplate code to achieve the same desired outcome. Given the final and immutable nature of an enum, creating additional enums through composition would be desirable, to maintain the properties that are consistent with other languages.

Its's just a shame that 3 years on this conversation is still going.

jmitchell38488 avatar Jul 16 '20 03:07 jmitchell38488

@jmitchell38488 I would drop a like to your comment, but your last sentence changed my mind. This is a needed discussion, since proposed solution would work, but it also implies the possibility of extending classes and interfaces this way. It is a big change which may scare some c++-like languages programmers from using typescript, since you basically end up with 2 ways of doing the same thing (class A extends B and class A { ...(class B {}) }). I think, both ways can be supported, but then we need extend for enums as well for consistency.

@masak wdyt? ^

sdwvit avatar Jul 19 '20 01:07 sdwvit

@sdwvit I'm not taking about changing the behaviour for creating classes and interfaces, I'm talking specifically about enums and creating them through composition. They're immutable final types, so we should not be able to extend in the typical inheritance fashion.

Given the nature of JS and the final transpiled value, there's no reason why composition can't be achieved. Sure would make working with enums more attractive.

jmitchell38488 avatar Jul 19 '20 01:07 jmitchell38488

@masak wdyt? ^

Hm. I think language consistency is a laudable goal, and therefore it's not a priori wrong to ask for a similar ... feature in classes and interfaces. But I think the case is weaker or nonexistent there, and for two reasons: (a) classes and interfaces already have an extension mechanism, and adding a second one provides little additional value (whereas providing one for enums would cover a use case that people have been coming back to this issue for for years); (b) adding new syntax and semantics to classes has a much higher bar for approval, since classes are in some sense from the EcmaScript specification. (TypeScript is older than ES6, but there's been an active effort to have the former stay close to the latter. That includes not introducing extra features on top.)

I think this thread has been open for a long time simply because it represents a worthy feature which would cover actual use cases, but it's yet to get a PR made for it. Making such a PR takes time and effort, more so than just saying you want the feature. :wink:

masak avatar Jul 19 '20 10:07 masak

Is anyone working on this feature?

SoundAsleep192 avatar Jul 28 '20 15:07 SoundAsleep192

Is anyone working on this feature?

My guess is no, since we haven't even finished the discussion on it, haha!

I do feel like we've come closer to a consensus on what this would look like. Since this would be a language addition, it would probably require a "champion" to push this proposal forward. I think someone from the TS team would need to come in and move the issue from "Awaiting feedback" to "Awaiting proposal" (or something similar).

julian-sf avatar Jul 28 '20 20:07 julian-sf

I am working on a prototype of it. Though I haven't gotten very far due to lack of time and unfamiliarity with the structure of the code. I do want to see this through and if there's no other movement, I'll continue on when I can.

JeffreyMercado avatar Jul 29 '20 00:07 JeffreyMercado

Would also love this feature. 37 months have passed, hopefully progress is made soon

elliotstoner avatar Sep 03 '20 18:09 elliotstoner

Notes from recent meeting:

  • We like the spread syntax, because extends implies a subtype, whereas “extending” an enum creates a supertype.

    enum BasicEvents {
      Start = "Start",
      Finish = "Finish"
    }
    enum AdvEvents {
      ...BasicEvents,
      Pause = "Pause",
      Resume = "Resume"
    }
    
  • The thought is that AdvEvents.Start would resolve to the same type identity as BasicEvents.Start. This has the implications that the types BasicEvents.Start and AdvEvents.Start would be assignable to each other, and the type BasicEvents would be assignable to AdvEvents. Hopefully this makes intuitive sense, but it’s important to note that this means the spread is not just a syntactic shortcut—if we expand the spread into what it looks like it means:

    enum BasicEvents {
      Start = "Start",
      Finish = "Finish"
    }
    enum AdvEvents {
      Start = "Start",
      Finish = "Finish",
      Pause = "Pause",
      Resume = "Resume"
    }
    

    this has different behavior—here, BasicEvents.Start and AdvEvents.Start are not assignable to each other, due to the opaque quality of string enums.

    Another minor consequence of this implementation is that AdvEvents.Start would probably be serialized as BasicEvents.Start in quick info and declaration emit (at least where there’s no syntactic context to link the member to AdvEvents—hovering over the literal expression AdvEvents.Start could plausibly result in quick info that says AdvEvents.Start, but it might be more clear to display BasicEvents.Start nonetheless).

  • This would only be allowed in string enums.

andrewbranch avatar Oct 07 '20 18:10 andrewbranch

I'd like to try on this one.

Kingwl avatar Oct 08 '20 15:10 Kingwl

To clarify: This is not approved for implementation.

There are two possible behaviors here, and they both seem bad.

Option 1: It's Actually Sugar

If spread really means the same as copying down the spreaded enum's members, then there will be a big surprise when people try to use the extending enum's value as if it were the extended enum's value and it doesn't work.

Option 2: It's Not Actually Sugar

The preferred option would be that spread works more like @aj-r's union type suggestion near the top of the thread. If that's the behavior people already want, then the existing options on the table seem strictly preferable for understandability's sake. Otherwise we're creating a new kind of string enum that doesn't behave like any other string enum, which is weird and seems to undermine the "simpleness" of the suggestion here.

Which behavior do people want, and why?

RyanCavanaugh avatar Oct 12 '20 13:10 RyanCavanaugh

I don't want option 1, because it leads to big surprises.

I do want option 2, but I would love to have enough syntax support to overcome the downside @aj-r mentioned, so I could write let e: Events = Events.Pause; from his example. The downside isn't terrible, but it is a place where the extended enum can't hide the implementation; so it's kind of gross.

dls314 avatar Oct 12 '20 13:10 dls314

I also think option 1 is a bad idea. I searched for references to this issue at my company and found two code reviews where it was linked, and in both cases (and in my personal experience), there's a clear need for elements of the smaller enum to be assignable to the larger enum type. I especially worry about one person introducing ... thinking it behaves like option 2, and then the next person getting really confused (or resorting to hacks like as unknown as Events.Pause) when more complex cases don't work.

There are already a lot of ways to try to get the behavior of option 2: plenty of snippets in this thread, plus various approaches involving string literal unions. My big worry with implementing option 1 is that it effectively introduces another wrong way to get option 2, and thus leads to more troubleshooting and frustration for people learning this part of TypeScript.

alangpierce avatar Oct 12 '20 19:10 alangpierce