以下代码可用于在 TypeScript 中创建 enum
:
enum e {
hello = 1,
world = 2
};
并且可以通过以下方式访问这些值:
e.hello;
e.world;
如何创建一个包含字符串值的enum
?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
最佳答案
typescript 2.4
现在有字符串枚举,因此您的代码可以正常工作:
enum E {
hello = "hello",
world = "world"
};
🌹
typescript 1.8
从 TypeScript 1.8 开始,您可以使用字符串文字类型为命名字符串值(枚举的部分用途)提供可靠且安全的体验。
type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay
foo = "asdf"; // Error!
更多:https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
旧版支持
TypeScript 中的枚举是基于数字的。
不过,您可以使用具有静态成员的类:
class E
{
static hello = "hello";
static world = "world";
}
你也可以直接说:
var E = {
hello: "hello",
world: "world"
}
更新:
基于能够执行类似 var test:E = E.hello;
的要求,以下满足此要求:
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);
关于typescript - 使用字符串值创建枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490560/