以下代码可用于在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中创建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中的字符串枚举:
字符串枚举是一个类似的概念,但是有一些细微的运行时差异,如下文所述。在string enum中,每个成员必须用string字面值或另一个string enum成员常量初始化。
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
虽然字符串枚举没有自动递增的行为,但字符串枚举的好处是它们很好地“序列化”。换句话说,如果你正在调试并且必须读取一个数值enum的运行时值,这个值通常是不透明的——它本身没有传达任何有用的含义(尽管反向映射通常会有所帮助),字符串enum允许你在代码运行时给出一个有意义且可读的值,与枚举成员本身的名称无关。 参考链接如下。
在这里输入链接描述
其他回答
打印稿0.9.0.1
enum e{
hello = 1,
somestr = 'world'
};
alert(e[1] + ' ' + e.somestr);
打印稿操场
这里有一个相当干净的解决方案,它允许继承,使用TypeScript 2.0。我没有在早期的版本上尝试过。
附加条件:该值可以是任何类型!
export class Enum<T> {
public constructor(public readonly value: T) {}
public toString() {
return this.value.toString();
}
}
export class PrimaryColor extends Enum<string> {
public static readonly Red = new Enum('#FF0000');
public static readonly Green = new Enum('#00FF00');
public static readonly Blue = new Enum('#0000FF');
}
export class Color extends PrimaryColor {
public static readonly White = new Enum('#FFFFFF');
public static readonly Black = new Enum('#000000');
}
// Usage:
console.log(PrimaryColor.Red);
// Output: Enum { value: '#FF0000' }
console.log(Color.Red); // inherited!
// Output: Enum { value: '#FF0000' }
console.log(Color.Red.value); // we have to call .value to get the value.
// Output: #FF0000
console.log(Color.Red.toString()); // toString() works too.
// Output: #FF0000
class Thing {
color: Color;
}
let thing: Thing = {
color: Color.Red,
};
switch (thing.color) {
case Color.Red: // ...
case Color.White: // ...
}
Typescript中的字符串枚举:
字符串枚举是一个类似的概念,但是有一些细微的运行时差异,如下文所述。在string enum中,每个成员必须用string字面值或另一个string enum成员常量初始化。
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
虽然字符串枚举没有自动递增的行为,但字符串枚举的好处是它们很好地“序列化”。换句话说,如果你正在调试并且必须读取一个数值enum的运行时值,这个值通常是不透明的——它本身没有传达任何有用的含义(尽管反向映射通常会有所帮助),字符串enum允许你在代码运行时给出一个有意义且可读的值,与枚举成员本身的名称无关。 参考链接如下。
在这里输入链接描述
你可以在最新的TypeScript中使用字符串枚举:
enum e
{
hello = <any>"hello",
world = <any>"world"
};
来源:https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
更新- 2016
最近我在React中使用的一种更健壮的方法是这样的:
export class Messages
{
static CouldNotValidateRequest: string = 'There was an error validating the request';
static PasswordMustNotBeBlank: string = 'Password must not be blank';
}
import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);
为什么不直接使用本地方式访问枚举的字符串呢?
enum e {
WHY,
NOT,
USE,
NATIVE
}
e[e.WHY] // this returns string 'WHY'