Issue
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
};
Solution
TypeScript 2.4
Now has string enums so your code just works:
enum E {
hello = "hello",
world = "world"
};
🌹
TypeScript 1.8
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
Legacy Support
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);
Answered By - basarat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.