Following code can be used to create an enum
in TypeScript:
enum e { hello = 1, world = 2 };
And the values can be accessed by:
e.hello; e.world;
How do I create an enum
with string values?
enum e { hello = "hello", // error: cannot convert string to e world = "world" // error };
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.
Now has string enums so your code just works:
enum E { hello = "hello", world = "world" };
🌹
Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).
type Options = "hello" | "world"; var foo: Options; foo = "hello"; // Okay foo = "asdf"; // Error!
More : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
Enums in TypeScript are number based.
You can use a class with static members though:
class E { static hello = "hello"; static world = "world"; }
You could go plain as well:
var E = { hello: "hello", world: "world" }
Update: Based on the requirement to be able to do something like var test:E = E.hello;
the following satisfies this:
class E { // boilerplate constructor(public value:string){ } toString(){ return this.value; } // values static hello = new E("hello"); static world = new E("world"); } // Sample usage: var first:E = E.hello; var second:E = E.world; var third:E = E.hello; console.log("First value is: "+ first); console.log(first===third);
In latest version (1.0RC) of TypeScript, you can use enums like this:
enum States { New, Active, Disabled } // this will show message '0' which is number representation of enum member alert(States.Active); // this will show message 'Disabled' as string representation of enum member alert(States[States.Disabled]);
Update 1
To get number value of enum member from string value, you can use this:
var str = "Active"; // this will show message '1' alert(States[str]);
Update 2
In latest TypeScript 2.4, there was introduced string enums, like this:
enum ActionType { AddUser = "ADD_USER", DeleteUser = "DELETE_USER", RenameUser = "RENAME_USER", // Aliases RemoveUser = DeleteUser, }
For more info about TypeScript 2.4, read blog on MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With