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

Which behavior do people want, and why?

Since code speaks louder than words, and using the example from the OP:

enum BasicEvents {
    Start = "Start",
    Finish = "Finish",
}
enum AdvEvents {
    ...BasicEvents,
    Pause = "Pause", // We added a new field
    Finish = "Finish2", // Oops, we actually modified a field in the parent enum
}

The TypeScript compiler should refuse to compile this code because we are modifying a field in the parent enum. But after removing the "Finish2" line, the TypeScript compiler should successfully handle it as one would normally expect with the spread operator.

This example showcases option 2, right? If so, then I desperately want option 2.

Zamiell avatar Oct 12 '20 20:10 Zamiell

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

I agree that option 2 is a little unsettling and it may be best to step back and think of alternatives. Here's an exploration of how it could be done without adding any new syntax or behavior to today's enums:

I think my suggestion in https://github.com/microsoft/TypeScript/issues/17592#issuecomment-449440944 gets the closest these days and might be something to work off of:

type Events = BasicEvents | AdvEvents;
const Events = {...BasicEvents, ...AdvEvents};

I see two main problems with that approach:

  • It's really confusing for someone learning TypeScript; if you don't have a solid grasp on the type space vs the value space, it looks like it's overwriting a type with a constant.
  • It incomplete since it doesn't allow you to use Events.Pause as a type.

I previously suggested https://github.com/microsoft/TypeScript/issues/29130 that would (among other things) address the second bullet point, and I think it could still be valuable, though it certainly would add a lot of subtlety to how names work.

One syntax idea that I think would address both points is an alternative const syntax that also declares a type:

// Declares a value and a type at the same time with the same name (just like `enum` and `class` already do).
// Requires the right-hand side to be either a unit type or an object where all values are unit types.
// The JS emit would just take out the word "type" and leave everything else.
const type Events = {...BasicEvents, ...AdvEvents};
...
const e: Events.Pause = Events.Pause;
...
// The syntax could also make this pattern more ergonomic.
const type INACCESSIBLE = "INACCESSIBLE";
const response: {name: string, favoriteColor: string} | INACCESSIBLE = INACCESSIBLE;

This would get closer to a world where enums aren't necessary at all. (To me, enums have always felt like they go against the TS design goals since they're an expression-level syntax with non-trivial emit behavior and nominal by default.) The const type declaration syntax would also let you create a structurally-typed string enum like this:

const type BasicEvents = {
  Start: 'Start',
  Finish: 'Finish',
};  // "as const" would be implicit for "const type" declarations.

Admittedly, the way this would need to work is that the type BasicEvents is shorthand for typeof BasicEvents[keyof typeof BasicEvents], which might be too focused for a generically-named syntax like const type. Maybe a different keyword would be better. Too bad const enum is already taken 😛.

From there, I think the only gap between (string) enums and object literals would be nominal typing. That possibly could be solved using a syntax like as unique or const unique type that basically opts into enum-like nominal typing behavior for these object types, and ideally for regular string constants as well. That would also give a clear choice between option 1 and option 2 when defining Events: you use unique when you intend Events to be a completely distinct type (option 1), and you omit unique when you want the assignability between Events and BasicEvents (option 2).

With const type and const unique type, there would be a way to cleanly union existing enums, and also a way to express enums as a natural combination of TS features rather than a one-off.

alangpierce avatar Oct 12 '20 21:10 alangpierce

What's happening here? 😅

authc0d3 avatar Oct 16 '20 11:10 authc0d3

wow from 2017 🤪, what more feedback do you need?

krailler avatar Oct 16 '20 11:10 krailler

what more feedback do you need?

Right here??? We don't just implement suggestions because they're old!

RyanCavanaugh avatar Oct 16 '20 13:10 RyanCavanaugh

what more feedback do you need?

Right here??? We don't just implement suggestions because they're old!

Yes. I was not sure which way it was.

Reading again and seeing also #40998 I think that is the best way... the emuns are objects and I think the spread is easier to merge/extend enums.

krailler avatar Oct 16 '20 15:10 krailler

I don't think I'm qualified enough to offer my opinion on language design, but I think I can give feedback as a regular developer.

I've come upon this issue a couple of weeks earlier in a real project where I wanted to use this feature. I ended up using @alangpierce's approach. Unfortunately, due to my responsibilities to my employer, I can't share the code here, but here are a few points:

  1. Repeating declarations (both type and const for a new enum) wasn't a big problem and didn't damage readability much.
  2. In my case, enum represented different actions for a certain algorithm, and there were different sets of actions for different situations in this algorithm. Using type hierarchy allowed me to verify that certain actions couldn't happen in compile time: this was the point of the whole thing and turned out to be quite useful.
  3. The code I wrote was an internal library, and while the distinction between different enum types was important inside the library, it didn't matter to outside users of this library. Using this approach, I was able to export only one type that was the sum type of all different enums inside, and hide the implementation detail.
  4. Unfortunately, I wasn't able to figure out an idiomatic and easy to read way to parse values of the sum type automatically from the type declarations. (In my case, different algorithm steps I mentioned were loaded from SQL database at runtime). It wasn't a huge issue (writing the parsing code manually was straightforward enough), but it would be nice if the implementation of enum inheritance would pay some attention to this issue.

Overall, I think that a lot of real projects with boring business logic would benefit a lot from this feature. Splitting enums into different subtypes would allow type system to check a lot of invariants that are now checked by unit tests, and making incorrect values unrepresentable by a type system is always a good thing.

golergka avatar Oct 17 '20 08:10 golergka

Hi,

Let me add my two cents here 🙂

My context

I have an API, with the OpenApi documentation generated with tsoa.

One of my model has a status defined like this:

enum EntityStatus {
    created = 'created',
    started = 'started',
    paused = 'paused',
    stopped = 'stopped',
    archived = 'archived',
}

I have a method setStatus that takes a subset of these status. Since the feature is not available, I considered duplicating the enum that way:

enum RequestedEntityStatus {
    started = 'started',
    paused = 'paused',
    stopped = 'stopped',
}

So my method is described this way:

public setStatus(status: RequestedEntityStatus) {
   this.status = status;
}

with that code, I get this error:

Conversion of type 'RequestedEntityStatus' to type 'EntityStatus' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

which I will do for now, but was curious and started searching this repository, when I found this. After scrolling all the way down, I didn't found anyone (or maybe I missed something) that suggests this use case.

In my use case, I don't want to "extend" from an enum because there's no reason that EntityStatus would be an extension of RequestedEntityStatus. I'd prefer to be able to "Pick" from the more-generic enum.

My Proposal

I found the spread operator better than the extends proposal, but I'd like to go further and suggest these:

enum EntityStatus {
    created = 'created',
    started = 'started',
    paused = 'paused',
    stopped = 'stopped',
    archived = 'archived',
}

enum RequestedEntityStatus {
    // Pick/Reuse from EntityStatus
    EntityStatus.started,
    EntityStatus.paused,
    EntityStatus.stopped,
}

// Fake enum, just to demonstrate
enum TargetStatus {
    {...RequestedEntityStatus},
    // Why not another spread here?
    //{...AnotherEnum},
    EntityStatus.archived,
}

public class Entity {
    private status: EntityStatus = 'created'; // Why not a cast here, if types are compatible, and deserializable from a JSON. EntityStatus would just act as a type union here.

    public setStatus(requestedStatus: RequestedEntityStatus) {
        if (this.status === (requestedStatus as EntityStatus)) { // Should be OK because types are compatible, but the cast would be needed to avoid comparing oranges and apples
            return;
        }

        if (requestedStatus == RequestedStatus.stopped) { // Should be accessible from the enum as if it was declared inside.
            console.log('Stopping...');
        }

        this.status = requestedStatus;// Should work, since EntityStatus contains all the enum members that RequestedEntityStatus has.
    }

    public getStatusAsStatusRequest() : RequestedEntityStatus {
        if (this.status === EntityStatus.created || this.status === EntityStatus.archived) {
            throw new Error('Invalid status');
        }
        return this.status as RequestedEntityStatus; // We have  eliminated the cases where the conversion is impossible, so the conversion should be possible now.
    }
}

More generally, this should work:

enum A { a = 'a' }
enum B { a = 'a' }

const a:A = A.a;
const b:B = B.a;

console.log(a === b);// Should not say "This condition will always return 'false' since the types 'A' and 'B' have no overlap.". They do have overlaps

In other words

I'd like to relax the constraints on enum types to behave more like unions ('a' | 'b') than opaque structures.

By adding those abilites to the compiler, two independent enums with the same values can be assigned to one another with the same rules as unions: Given the following enums:

enum A { a = 'a', b = 'b' }
enum B { a = 'a' , c = 'c' }
enum C { ...A, c = 'c' }

And three variables a:A, b:B and c:C

  • c = a should work, because A is just a subset of C, so every value of A is a valid value of C
  • c = b should work, since B is just 'a' | 'c' which are both valid values of C
  • b = a could work if a is known to be different from 'b' (which would equal to the type 'a' only)
  • a = b, likewise, could work if b is known to be different from 'c'
  • b = c could work if c is known to be different from 'b' (which would equal to 'a'|'c', which is exactly what B is)

or maybe we should need an explicit cast on the right-hand sides, as for the equality comparison ?

About enum members conflicts

I'm not a fan of the "last wins" rule, even if it feels natural with the spread operator. I'd say that, the compiler should return an error if the either a "key" or a "value" of the enum is duplicated, unless both key and value are identical:

enum A { a = 'a', b = 'b' }
enum B { a = 'a' , c = 'c' }
enum C {...A, ...B } // OK, equivalent to enum C { a = 'a', b = 'b', c = 'c' }, a is deduplicated
enum D {...A, a = 'd' } // Error : Redefinition of a
enum E {...A, d = 'a' } // Error : Duplicate key with value 'a'

Closing

I find this proposal quite flexible and natural for TS devs to work with, while allowing more type safety (compared to as unknown as T) without actually changing what an enum is. It just introduces a new way to add members to enum, and a new way to compare enums to each others. What do you think? Did I miss some obvious language architecture issue that makes this feature unachievable?

jeremyVignelles avatar Nov 27 '20 13:11 jeremyVignelles

As a workaround, I'm trying Union Types with a guaranteed type property—much like Redux actions.

type Difficulty =
  | { type: 'beginner'; weight: 1 }
  | { type: 'intermediate'; weight: 2 }
  | { type: 'advanced'; weight: 3 };

type PreferredDifficulty = Difficulty | { type: 'random' };

And I use these for different things in my app. For example an Exercise can't have a randomly difficulty...

interface Exercise {
  name: string;
  difficulty: Difficulty;
}

But a user's workout sure can!

interface User {
  name: string;
  preferredDifficulty: PreferredDifficulty;
}

const generateWorkout = (w: Workout, u: user) => {
  if (u.preferredDifficulty.type === 'random') {
    // pick random exercises
  } else {
    // pick exercises suited to their preferred difficulty
  }
}

yazeedb avatar May 09 '21 19:05 yazeedb

Hi @RyanCavanaugh, is this feature on the roadmap?

john-larson avatar Aug 31 '21 12:08 john-larson

Hello, any progress?

emil45 avatar Nov 07 '21 13:11 emil45

So here's the most likely answer at this point - we're probably not going to touch enums for a bit as there's discussion of introducing them to JS; that said, discussion here can help drive the design direction of JS.

DanielRosenwasser avatar Dec 06 '21 22:12 DanielRosenwasser

Coming back to this, I don't fully understand the "sugar"/"no sugar" distinction and why it's necessary. Is it just desirable to be able to use either enum for the other? Or is it just that for enum E { ...F }, F is assignable to E?

If it's the latter, could we make a world where for each member of enum E { ...F }, the type of that member is a supertype the corresponding member of F?

DanielRosenwasser avatar Dec 06 '21 22:12 DanielRosenwasser

What do you think of my proposal here ?

My suggestion is to treat the members independently as if they were a type union, to allow them to be assigned in both directions as long as they have a sufficient overlap. using the spread operator allows to create a superset of an enum more simply. The cherry pick syntax ({ OtherEnum.a, OtherEnum.b}) allows to create a subet of an enum.

Do you have a link to the JS proposal?

jeremyVignelles avatar Dec 07 '21 06:12 jeremyVignelles

IMHO, TypeScript enums should be considered bad practice (and hopefully eslinted-out at some point in future).

I believe they originate in times of TypeScript is superset of JavaScript, even though IMO this is contrary to the Design Goals (points 3, 4, 8 and 9).

As I hope that now we are back in Typescript is JavaScript + Types world, we should promote idiomatic JS with typechecks instead of custom runtime constructs, that is exactly the approach suggested by @CyberMew above:

type BEs = "Start" | "Finish";

type AEs = BEs | "Pause" | "Resume";

let example: AEs = "Finish"; // there is even autocompletion

Some additional reference: Should You Use Enums or Union Types in Typescript?

whut avatar Feb 11 '22 11:02 whut

for now what I have been doing

So here's the most likely answer at this point - we're probably not going to touch enums for a bit as there's discussion of introducing them to JS; that said, discussion here can help drive the design direction of JS.

Thank you! For others... for now what I have been doing is this:

type Gender = 'male' | 'female' | 'pansexual' | ...
const Gender = {
  Male: 'male' as Gender,
  Female: 'female' as Gender,
  Pansexual: 'pansexual' as Gender,
...
}

this allows

const somonesGender: Gender = 'male' //  a "string" value coming from backend or from radio button that can be assigned and treated as "Gender"
const somonesElsesGender = Gender.Male  // this is allowed too and is treated as a "Gender"

nazarioa avatar Feb 17 '22 01:02 nazarioa

@nazarioa

You can inherit the type from the object, so you don't need to define the values twice.

type ConstEnum<T, V = string> = Extract<T[keyof T], V>

const Gender = {
  Male: 'male',
  Female: 'female'
} as const
type Gender = ConstEnum<typeof Gender>

const gender: Gender = Gender.Female


const ExtendedGender = {
  ...Gender,
  Pansexual: 'pansexual'
} as const
type ExtendedGender = ConstEnum<typeof ExtendedGender>

let extendedGender: ExtendedGender = ExtendedGender.Pansexual
extendedGender = ExtendedGender.Female

freakzlike avatar Feb 17 '22 06:02 freakzlike

So here's the most likely answer at this point - we're probably not going to touch enums for a bit as there's discussion of introducing them to JS; that said, discussion here can help drive the design direction of JS.

@DanielRosenwasser Ugh, looks like I missed your comment.

For the reference this is probably where the mentioned discussion happens: https://github.com/Jack-Works/proposal-enum

whut avatar Feb 22 '22 23:02 whut

Please, @nazarioa and @freakzlike, refrain from two things:

  1. mixing up sexual orientation with gender. Pansexuality is a sexual orientation.
  2. limiting gender and sexual orientation options. Those are not clear cut and are based on the individual's experiences.

Also, consider if those pieces of data are needed. Most often they're not. If they are, have at least an "Other" option, although an open field would be better.

patriciaverso avatar Apr 11 '22 19:04 patriciaverso

While @patriciavillela's comment might seem like a detour from the main topic, I see a way to connect it to (what I see as) the main important property to preserve in all of this:

The original enum must not be affected by the extension.

We like enums because of their "closed-world" property — that's the one that gives us totality/coverage checking in switch statements, for example. If the implementation of this issue affects that guarantee, we've all lost something valuable.

From a social perspective, there's simply no way to get the original enum author's blessing — the enum is and remains closed. @patriciavillela was not the original author of the Gender enum, but it's possible to imagine the original author similarly objecting to their enum being extended.

From this point of view, the term "extending" (in the issue topic) is a misnomer; enums simply do not extend. "Inheriting" is half-wrong, half-OK, I guess — you get the original enum's values, but you do not in any sense participate in the original enum's type.

@RyanCavanaugh wrote:

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.

I think the big surprise here is relative to expectations set up by terms like "extending". Since we can't actually deliver on that promise without breaking a fundamental guarantee of enums (that of being closed), I'm fine with Option 1, and I think it can be made much less surprising by avoiding terms like "extending".

Regarding this:

So here's the most likely answer at this point - we're probably not going to touch enums for a bit as there's discussion of introducing them to JS; that said, discussion here can help drive the design direction of JS.

I guess what I should really be doing is head over to the tc39 repository and defend JavaScript enums against the extends keyword. 😄 This seems to be the issue for doing that.

masak avatar Apr 12 '22 02:04 masak