TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Proposal: String enums

Open jbondc opened this issue 11 years ago • 70 comments

A string enum is inferred by looking at the constant value of the initializer of its first member:

enum stringsInferred {
   a = "a",
   b, // "b"
   c  // "c"
}

Or it is declared using a string index:

enum stringsDeclared {
   [prop: string] : string;
   a, // "a"
   B, // "B"
   c  // "c"
}

The auto initialized value on an enum is its property name.

Inferred enum special case

enum stringsLowerCase {
   Shoes = "shoes", // If the first member has lowercase chars, then lowercase all other member values
   Boots, // "boots"
   Feet  // "feet"
}

jbondc avatar May 17 '15 14:05 jbondc

:+1:

We should definitely be able to use enums with string values. Even a const enum with compile-time string literals (that are always safe to inline) would be helpful already, mainly for …

  • restricting variables to a set of known string values, and
  • avoiding misspellings.

I'm not sure the automagical upper- and lowercasing described underneath Inferred enum special cases is such a good idea, though. I'd rather spell all cases exactly like they should be stringified:

enum stringsUpperCase {
   Shoes = "SHOES",  // "SHOES"
   BOOTS,            // "BOOTS"
   Feet              // "Feet"
}

mariusschulz avatar Jun 06 '15 11:06 mariusschulz

Can this be generalized to other types (with the constraint that all types must be initialized - no value can be inferred)?

dead-claudia avatar Jul 11 '15 03:07 dead-claudia

@jbondc

I agree, and this could be the other special case (where value inference already exists for numbers). Also, FWIW, I made a post on that bug with a few more specific suggestions IIRC. It just wasn't on the top of my mind at the time.

dead-claudia avatar Jul 14 '15 20:07 dead-claudia

@jbondc

And I feel this syntax is a little repetitive in the [prop: string]: string part. Couldn't the syntax be modified to have the type after the enum name, instead of in the body? Maybe this syntax, to borrow your example?

enum strings : string {
   Shoes,           // "Shoes"
   BOOTS,            // "BOOTS"
   Feet              // "Feet"
}

dead-claudia avatar Jul 16 '15 06:07 dead-claudia

@jbondc Any advantages to that over my recent proposal? I don't think that regex-based solution is really that helpful in practice. All that regex does there is enforce type names, something better left to a linter as opposed to the main compiler. And it looks a little out of place compared to the enum entries. And as you said in the other thread, it will complicate the parser and compiler a little, likely more than it should.

And as for extending enums, that's not very good practice, anyways. And it's generally not possible among other TypeScript users. Mine allows for such extensions, but you can only truly extend them in the same module or private namespace declaration, unless you're writing a definition file. That's because of the module wrapper emitted around every namespace declaration. So, for most purposes, you can't really extend them in the first place. Also, the spec currently requires that same-named declarations within the same root to add properties to the same enum.

dead-claudia avatar Jul 16 '15 11:07 dead-claudia

:+1: for string (const) enums

lazdmx avatar Jul 16 '15 19:07 lazdmx

My current workaround looks something like this (this is a real-world, copy-and-paste code example):

class Task {
  ..
  static State = { 
    Unstarted: "Unstarted", 
    Started: "Started", 
    Completed: "Completed", 
    Faulted: "Faulted", 
    Canceled: "Canceled"
  }
}

let task = new Task();
..
if (task.state === Task.State.Completed) // The declared type of task.state is "string" here.
  console.log("Done!");

This also gives a nice encapsulation into the class type that I find appealing (through the static modifier).

Replicating this through enum would require several different enhancements. I will consider posting a separate proposal for class encapsulated enums if that hasn't been proposed before.

I think having string enums would be very useful (maybe "necessary" should be the right word here). Automatic inferring of things like letters would be problematic because of locale and language issues (every language would have its own letters and ordering). Automatic lowercasing/uppercasing would also be impacted from similar issues (every language has different lower/uppercasing rules), and seems to me like a minor detail/enhancement at this point.

rotemdan avatar Sep 04 '15 10:09 rotemdan

Maybe the string keyword would lend itself to be included in the declaration:

string enum PromiseState {
    Pending,
    Fulfilled,
    Rejected
}

In the above example, the string values of the cases would equal their names. They could be overwritten like this:

string enum PromiseState {
    Pending = "pending",
    Fulfilled = "fulfilled",
    Rejected = "rejected"
}

mariusschulz avatar Sep 04 '15 13:09 mariusschulz

This may turn out a bit long for a const enum that is also exported:

export const string enum PromiseState {
    Pending,
    Fulfilled,
    Rejected
}

So maybe an alternative using some sort of a psuedo-generic type parameter?

export const enum PromiseState<string> {
    Pending,
    Fulfilled,
    Rejected
}

Due to issues with different languages, alphabets, and locales it would be difficult to apply a correct conversion to lowercase/uppercase in many languages other than English. So just preserving the original casing and allowing custom ones through = seems like a reasonable compromise.

rotemdan avatar Sep 04 '15 14:09 rotemdan

Hi, what is the actual state of this proposal? can we have a roadmap to know when will be implemented in the language? Thanks

Gambero81 avatar Sep 19 '15 17:09 Gambero81

@Gambero81 See #1206 for a more up-to-date version of this.

dead-claudia avatar Sep 20 '15 03:09 dead-claudia

Can this be closed in favor of #1206? It's more general, which is better IMHO.

dead-claudia avatar Sep 20 '15 03:09 dead-claudia

Union and intersection types would already exist with my proposal. You could achieve the same thing.

On Sun, Sep 20, 2015, 09:17 Jon [email protected] wrote:

@impinball https://github.com/impinball No, added this here strictly for discussing a string enum & use cases. e.g. can you interest two string enums?

enum a { hello = "hello" } enum b { world = "world" } let c = a & b; let d = typeof a & typeof b;

— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/3192#issuecomment-141784947 .

dead-claudia avatar Sep 21 '15 12:09 dead-claudia

Using of String are really neat feature. In our 20k loc project we still use workarounds. Apart, using objects as enum values (like in #1206 or http://stackoverflow.com/a/15491832/1224258) are risky - comparison fails after any Enums serialization/de-serialization or deepcopy (angular.copy).

vitrilo avatar Sep 29 '15 10:09 vitrilo

Probably better if https://github.com/Microsoft/TypeScript/issues/1003 is done instead

basarat avatar Sep 30 '15 06:09 basarat

@basarat I think both have their uses. A primitive enum (excluding symbols) could be seen as the union of their values in that sense. And also, I believe that should be expanded to also include numbers.

dead-claudia avatar Sep 30 '15 06:09 dead-claudia

I made a relevant response over there on #1003.

dead-claudia avatar Sep 30 '15 06:09 dead-claudia

@jbondc I tried to include those, but I didn't get a very positive response from it.

dead-claudia avatar Sep 30 '15 17:09 dead-claudia

@basarat Thanks, I've just discovered related #1003, #1295. Great proposals/ideas! My understanding #1003 (string literal union type) vs #3192 (string enums) is following:

  • String enums are simple, straightforward approach
  • #1003 - are more wider idea, which are may be both: multi-purpose (like for type guards) solution and space for funky/unwanted/corner cases
  • Syntax are RADICALLY different (which not obvious on first site):
    var var1 = MyEnum.Kind1; //string enum.
    var var2 = "kind1"; //string literal union type - NO compiler type-checking! 
    var var3:MyUnionEnum = "kind1"; //string literal union type with compiler type-checking 
  • Readability: IMHO, String enums have better readability. Moreover, in many languages enum types make uppercased to highlight limited possibilities and static nature.
  • IDE support. Tools are all for us! Possible, implementing auto-complete for #1003 (string literal union type) may be significantly harder inside IDEs comparing to #3192 (string enums). Not because of complexity of union-type concept, also because IDE should introduce in-natural auto-complete inside string literals: "kind1" (should suggest kind2,kind3.. if this is union type).

Apart, from all above, Javascript ecosystem generally encourage wide usage of string literals. As result, like in #1003, #1295 IDEs/Tools will be forced to support special meaning of string literals, like as enum constants/properties names etc, not just meaningless text to output.

vitrilo avatar Sep 30 '15 20:09 vitrilo

:+1: This feature would be great.

Right now, the enums are a bit counter intuitive from a JavaScript usage perspective. They work well for internal TypeScript code but not so much when code is used in third party apps.

It would be especially useful for bridging the gap between both worlds:

Example:

sdk.ts
--------

export enum Environments {
  SANDBOX,
  PRODUCTION
}

interface ClientOptions {
  id: string;
  secret: string;
  env?: Environments;
}

export class Client {
  constructor(public options: ClientOptions) {}

  hostname(): string {
    let part = 'sandbox';

    if (this.env === Environments.PRODUCTION) {
      part = 'api';
    }

    return `rest.${part}.example.com`;
  }
}

caller.js
----------

var client = new Client({
  id: 'id',
  secret: 'secret',
  env: 'production'
});

Right now, client.hostname() will fail because Environments.PRODUCTION === 1.

jtheoof avatar Nov 20 '15 19:11 jtheoof