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:

mrcrowl avatar Nov 26 '15 09:11 mrcrowl

My two cents while this gets approved:

Not that you can pretend this feature like this.

    export enum OrderType {
        Ascending = "Ascending" as any,
        Descending = "Descending" as any,
    }

The benefit is that then your API is better documented, asking for an OrderType instead of a dirty string.

The problem is that you need to repeat the identifier for the common case when declaring.

Also, when using it, you have to cast from string -> any -> OrdeType:

var orderType: OrderType = "Ascending"; //Error
var orderType: OrderType = "Ascending" as any; //OK

olmobrutall avatar Dec 16 '15 20:12 olmobrutall

Edit: Maybe don't do this since string literal types are still in flux.


Here's a way you'll be able to emulate string enums in typescript@next. Taking a modified version of Esprima's Syntax object:

function strEnumify<T extends { [prop: string]: "" | string }>(obj: T) {
    return obj;
}

export const Syntax = strEnumify({
    AssignmentExpression: 'AssignmentExpression',
    AssignmentPattern: 'AssignmentPattern',
    ArrayExpression: 'ArrayExpression',
    ArrayPattern: 'ArrayPattern',
    ArrowFunctionExpression: 'ArrowFunctionExpression',
    BlockStatement: 'BlockStatement',
    BinaryExpression: 'BinaryExpression',
    BreakStatement: 'BreakStatement',
    CallExpression: 'CallExpression',
    CatchClause: 'CatchClause',
    ClassBody: 'ClassBody',
    ClassDeclaration: 'ClassDeclaration',
    ClassExpression: 'ClassExpression',
    // ...
    ThisExpression: 'ThisExpression',
    ThrowStatement: 'ThrowStatement',
    TryStatement: 'TryStatement',
    UnaryExpression: 'UnaryExpression',
    UpdateExpression: 'UpdateExpression',
    VariableDeclaration: 'VariableDeclaration',
    VariableDeclarator: 'VariableDeclarator',
    WhileStatement: 'WhileStatement',
    WithStatement: 'WithStatement',
    YieldExpression: 'YieldExpression'
});

image

(@ariya)

The problem is that you can't do something like the following:

let kind = Syntax.VariableDeclaration;
kind = Syntax.WithStatement;

DanielRosenwasser avatar Dec 16 '15 23:12 DanielRosenwasser

@olmobrutall thanks for perfect workaround! Well serialized/deserialized, apart from unreadable numeric enums inside json. Below working even in v1.4:

  enum OrderType { Ascending = <any>"Ascending", Descending = <any>"Descending" }

vitrilo avatar Dec 17 '15 23:12 vitrilo

@DanielRosenwasser I would generally prefer to use const numeric enums where possible (a JS-to-ESTree AST parser couldn't for spec reasons) for that just for memory and performance reasons (both reduced for free). But I could see merit in a string enum to hold error messages like what jshint uses.

dead-claudia avatar Dec 18 '15 01:12 dead-claudia

@olmobrutall @DanielRosenwasser @vitrilo there workaround are good but a good feature of string enum should be to inlining string const enum without emit js as done with standard const enum, unfortunally for this porpouse all these workaround doesn't work

Gambero81 avatar Dec 18 '15 06:12 Gambero81

@Gambero81, of course having native support from the language will be the best solution, simplifying the declaration (no repetition for the simple cases), and the usage (no casting).

About const enums, we already have the syntax and the concept for normal enums, it will make sense just to extrapolate the same concepts for string enums.

export const enum Color extends string{
   red,
   blue,
   darkViolet= "dark-violet"
}

olmobrutall avatar Dec 18 '15 06:12 olmobrutall

:+1: current project: accessing REST service with generated TypeScript interfaces and enums. Enums are not usable, since service needs strings in JSON payload.

Is there a way to serialize / deserialize JSON and convert enum instances on-the-fly?

hgoebl avatar Jan 24 '16 14:01 hgoebl

I've just found this today: https://blog.wearewizards.io/flow-and-typescript-part-2-typescript

TLDR; Typescript is better than flow but has no string enums :-1:

The only issues we have encountered so far (and would love help to resolve!) are:

  • webpack building the previous version: adding an empty line and saving a file re-triggers a compilation but can be frustrating
  • no string enums: we want to keep human readable enum members but TypeScript only supports int enums

Any news on this issue? Any change this gets implemented.

olmobrutall avatar Jan 28 '16 19:01 olmobrutall

I agree.. string enum is a MUST!! (in particular const string enum)

still hope to show it soon...

Gambero81 avatar Jan 28 '16 21:01 Gambero81

I just read that the new TypeScript 1.8 beta has "string literal types": https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#string-literal-types

That seems to solve exactly this use case, right?

type Order = "Ascending" | "Descending";

sampsyo avatar Jan 28 '16 21:01 sampsyo

string literal is not string enum..

Gambero81 avatar Jan 28 '16 21:01 Gambero81

Wow didn't know that. With autocompletion they can be a even better alrernative!

column.order = //autocompletion here please!
               //"Ascending"
               //"Descending"

Thanks TS Team!

olmobrutall avatar Jan 28 '16 22:01 olmobrutall

@olmobrutall I have two issues created for your tracking :rose: https://github.com/Microsoft/TypeScript/issues/5602 https://github.com/Microsoft/TypeScript/issues/6705

basarat avatar Jan 28 '16 22:01 basarat

Edit: See better way here.

String enums can be mimicked by merging a string literal type and module this way:

type MyStringEnum = "member1" | "member2";

module MyStringEnum {
    export const Member1: MyStringEnum = "member1";
    export const Member2: MyStringEnum = "member2";
}

Full example.

If at all, it seems it's only worth implementing enum MyStringEnum { myMember = "my member" } for syntactic sugar.

dsherret avatar Feb 07 '16 19:02 dsherret

@dsherret nice point!

olmobrutall avatar Feb 07 '16 22:02 olmobrutall

@dsherret s/module/namespace/g. module in that context is deprecated, and it has been for a while. :smile:

dead-claudia avatar Feb 08 '16 08:02 dead-claudia

This works just like a string enum too:

type MyStringEnum = "member1" | "member2";

const MyStringEnum = {
    Member1: "member1" as MyStringEnum,
    Member2: "member2" as MyStringEnum
};

Updated example.

dsherret avatar Feb 08 '16 13:02 dsherret

Clever hack @dsherret but why is this not implemented yet? +1 for string enums!

amcdnl avatar Jun 08 '16 23:06 amcdnl

@amcdnl I feel the more general #1206 is more helpful than just this.

dead-claudia avatar Jun 11 '16 15:06 dead-claudia