Allow enums of types other than number
I'm reopening this issue, because it was closed with the move from codeplex, and doesn't seem to have been re-opened. https://typescript.codeplex.com/workitem/1217
I feel like this is very important for a scripting language.-- Especially for objects that are passed back and forth over web service calls.-- People generally don't use integer based enums in json objects that are sent over the wire, which limits the usefulness of the current enum implementation quite a bit.
I would like to re-propose the original contributor's suggestions verbatim.
From the original proposal
As in the title, and as discussed extensively here, it would be very helpful to allow enums of types other than number. At the very least, if allowing arbitrary types is too much work, string enums should be allowed. The current codegen for enums actually works with strings as-is, the compiler just flags errors.
Consider:
enum Dog{ Rover = 'My Dog', Lassie = 'Your Dog' }
alert(Dog.Rover);
As of 0.9, this gets to compiled to:
var Dog; (function (Dog) { Dog[Dog["Rover"] = 'My Dog'] = "Rover";
Dog[Dog["Lassie"] = 'Your Dog'] = "Lassie"; })(Dog || (Dog = {}));
alert(Dog.Rover);
which is 100% functioning JavaScript that works as you expect it to.
In addition, the whole concept of "overloads on constants" would be a lot cleaner with a string-based enum:
interface Document { createElement(tagName: TagName): HTMLCanvasElement; }
enum TagName{ Canvas = "canvas", Div = "div", Span = "span" }
var a = createElement(TagName.Canvas); //a is of type HTMLCanvasElement
Closed Jul 28 at 5:18 PM by jonturner
As part of our move to GitHub, we're closing our CodePlex suggestions and asking that people >move them to the GitHub issue tracker for further discussion. Some feature requests may already >be active on GitHub, so please make sure to look for an existing issue before filing a new one.
You can find our GitHub issue tracker here: https://github.com/microsoft/typeScript/issues
Changed the one example from the original for the Document interface. It seems that you would only specify the name of the enum.-- Values passed in would become bounded to the use of the enum constants (and possibly to free-form string literals, where their values can be statically determined to be within the enum's domain values)
@jhlange I think tagged unions would automatically cater for this use case nicely : https://github.com/Microsoft/TypeScript/issues/1003
@basarat That seems interesting from a theoretical standpoint, and I can definitely see uses for it.
It would solve my case.--At least giving some level of intellisense and compile-time validation.
I personally believe accessing enum constant fields makes for a much more natural experience for non-functional languages (and at least has parity with enums, which is what they they really are. I really don't think we should create a new concept for a construct that already exists. That will be confusing to too many people).
I would love this when I deal with C++ enums compiled by Emscripten.
// C++
enum Month {
Jan, Feb, Mar
};
// I can do this, but they really are not numbers!
declare enum Month {
Jan, Feb, Mar
}
interface EmscriptenEnum {
value: number; /* some more properties ... */
}
interface Month extends EmscritenEnum {
}
declare module Month {
var Jan: Month;
var Feb: Month;
var Mar: Month;
}
// Month.Jan.value == 0, Month.Feb.value == 1, ...
C#/C++ lets you define base type of enum, although restricted to numeric type. I would like to be able to do the same but generalized to arbitrary type.
It should work with builtin types like string, so:
enum Foo extends string {
BAR,
BAZ = "surprise"
}
compiles to:
var Foo;
(function (Foo) {
Foo["BAR"] = "BAR";
Foo[Foo["BAZ"] = "surprise"] = "BAZ";
})(Foo || (Foo = {}));
but also user types, to handle enum object pattern that is used by enums in Java and common in other languages (as requested above):
interface IFoo {
id: string;
code: number;
}
enum Foo extends IFoo {
BAR = { id: "BAR", code: 123 },
BAZ = { id: "", code: 0 }
}
compiles to:
var Foo;
(function (Foo) {
Foo["BAR"] = { id: "BAR", code: 123 };
Foo["BAZ"] = { id: "", code: 0 };
})(Foo || (Foo = {}));
Perhaps with a convention that if interface has fields id and/or code (or ordinal as in Java) they can be omitted in initializer and filled by compiler.
How would this work?
enum Test {
Foo = "Bar",
Bar = "Baz",
Baz = "Foo"
}
Either compilation error or omit generation of reverse mapping for Bar. I'm not sure which one I prefer.
In fact I'd prefer if TypeScript didn't generate reverse mapping in the same object. Perhaps all reverse mappings (for number based enums too) should go inside some property, say Test.__reversed.
In my mind these really need to compile down to plain strings. String enums are already heavily used in json objects for Web services. In my opinion this is one of the main use cases for string based enums.-- another example is in the second post-- being able to define the domain values for predefined Javascript apis.
If it isn't possible to define strongly typed interfaces for these cases, because typescript uses a different methodology in its implementation, the implementation would be purely academic. On Dec 30, 2014 3:16 PM, "Marcin Wisnicki" [email protected] wrote:
In fact I'd prefer if TypeScript didn't generate reverse mapping in the same object. Perhaps all reverse mappings (for number based enums too) should go inside some property, say Test.__reversed.
— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/1206#issuecomment-68409570 .
I think the first thing should be strings const enum. This is definitely the most useful feature. Many APIs has JSON with small amount of possible string values and currently you must use 'string' type rather then a correct subset. In that case I even think the names are not needed since you can pass only the correct string.
const enum A {
"x",
"y",
"z"
}
var a : A;
a = // Intellisense suggest "x", "y" or "z"
a = "x"; // OK
a = "b"l // Error
My concern with the const enum approach is that it will lead to cases where the value can not be determined to be conforming when being passed into an API. (would this be a warning?, what happens if you get that warning? do you have to add casts all over the place to mitigate the warning?).
If you treat them as something that can never be converted to or from a string, they will do exactly what they need to do.-- It should work exactly like the integer enums, with the exception that the values are strings. I think it would be fine if the keys and values are locked together, meaning that
const enum A {
"x",
"y",
"z"
}
Could be fine, but any string assignments without casts should fail.
public myfunc(someRandomInput: string) {
var a : A;
a = // Intellisense suggest A.x A.y A.z
a = "x"; // Error, it is overkill to support this special case. Just use A.x like a regular enum
a = A.x; // OK
a = "b"; // Error
a = someRandomInput; // Error, can not always be determined to be conforming.
}
In cases where they are converted from a string, a cast should be used.-- But even then, behavior like that can indicate that an input did not come from a proper source.
Additionally, this will help tooling like the the schema validation/generators to appropriately generate the appropriate validation code.-- Schema validation is going to become even more important in times to come.--One of my big concerns with javascript is general is the lack of validation.-- Now that people are running servers on this stuff.
As far as I can tell, the bulk of the work needed to get this done is removing one validation/compiler error against enum definitions (assigning types other than number).-- There might be some smarts to make sure people don't directly assign numbers to enum, but they shouldn't be doing that without a cast anyway either...
How about using generics for enum?
Current existing enum means enum<number>. So we can extend it to enum<string> or other types:
enum<string> Foo1 {
BAR, // default value is "BAR".
BAZ = "x" // also you can specify the vaule.
}
var e: Foo1 = Foo1.BAR; // ok
var s: string = Foo1.BAR; // ok
var n: number = Foo1.BAR; // error
enum<boolean> Foo2 {
BAR = true, // assigning is required. only number and string enum have default value.
BAZ = false
}
You can use every type for enum like enum<YourFavoriteType> and there is no breaking change.
Base type syntax makes more sense IMHO and is already familiar to C# developers.
+1 for the generics suggestion.
and Closure Compiler uses @enum {string}, similar to generics.
/**
* @enum {string}
*/
var Foo = {
BAR: 'BAR',
BAZ: 'BAZ'
};
Also default type of enum in Closure is number. It's in common with TypeScript's case.
If the type of an enum is omitted, number is assumed. https://developers.google.com/closure/compiler/docs/js-for-compiler
+1 for the generics syntax. I just need some sort of functionality. Here's my use case: I'm wanting to convert this bit of ES6 + Lodash into something I can more conveniently statically check. (Note: the boilerplate is because I use it for other things as well, things that would have to be generated at build time to statically type-check.)
// Enum
const tokenTypes = makeEnumType(([value, length]) => ({value, length}));
export const Tokens = tokenTypes({
OpenCurved: ['(', 1],
CloseCurved: [')', 1],
OpenBracket: ['[', 1],
CloseBracket: [']', 1],
OpenCurly: ['{', 1],
CloseCurly: ['}', 1],
Identifier: ['Identifier', 0],
String: ['String', 0],
EOF: ['EOF', 0],
});
// Utilities
function deepFreeze(obj) {
Object.freeze(obj);
_.forOwn(obj, value => typeof value === 'object' && deepFreeze(obj));
return obj;
}
_.mixin({
removeProto(obj) {
let ret = Object.create(null);
_.forOwn(obj, _.partial(_.assign, ret));
return ret;
},
freeze: deepFreeze,
});
function mapObject(obj, f) {
let ret = Object.create(Object.getPrototypeOf(obj));
forOwn(obj, (value, i) => ret[i] = f.call(obj, value, i, obj));
return ret;
}
function makeEnumType(transformer) {
return obj => _.chain(mapObject(obj, transformer))
.removeProto()
.freeze()
.value();
}
The best I can currently do in the first case is this (the second is similar):
interface TokenType {
type: string;
value: string;
}
function type(value: string, length: number): TokenType {
return {value, length};
}
class TokenTypes {
// This shouldn't be called as a constructor...but it still type-checks.
static OpenCurved: TokenType = type('(', 1);
static CloseCurved: TokenType = type(')', 1);
static OpenBracket: TokenType = type('[', 1);
static CloseBracket: TokenType = type(']', 1);
static OpenCurly: TokenType = type('{', 1);
static CloseCurly: TokenType = type('}', 1);
static Identifier: TokenType = type('Identifier', 0);
static String: TokenType = type('String', 0);
static EOF: TokenType = type('EOF', 0);
}
With the above syntax, I could use the following:
enum<TokenType> TokenTypes {
OpenCurved = type('(', 1),
CloseCurved = type(')', 1),
OpenBracket = type('[', 1),
CloseBracket = type(']', 1),
OpenCurly = type('{', 1),
CloseCurly = type('}', 1),
Identifier = type('Identifier', 0),
String = type('String', 0),
EOF = type('EOF', 0),
}
This is where enums can really help.
(The boilerplate is mainly for places where a preprocessor would be helpful.)
@jbondc I like it.
You've picked the simple, obvious and intuitive solution, that can enforce type safety in many of the situations that some of the above options can't without a full static analysis of a program.-- It additionally would support creating straight forward domain bound json schma validations right from the typescript definition.
Any interest in #2491 ?
+1 for this and I am suggesting supporting all primitive types for enum values. Just like Swift. This is the syntax in Swift which I really like:
enum Audience: String {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
}
I would like to mention that, because of ECMAScript language limitations
themselves, const enums should be limited to non-Symbol primitives. Because
{} !== {} and Symbol("foo") !== Symbol("foo"), other enums can't be
inlined.
I do feel this would be incredibly useful, though.
On Tue, Jun 16, 2015, 16:41 Mohsen Azimi [email protected] wrote:
+1 for this and I am suggesting supporting all primitive types for enum values. Just like Swift. This is the syntax in Swift which I really like:
enum Audience: String { case Public = "Public" case Friends = "Friends" case Private = "Private" }
— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/1206#issuecomment-112563174 .