以下代码可用于enum在TypeScript中创建:
enum e {
hello = 1,
world = 2
};
Run Code Online (Sandbox Code Playgroud)
并且可以通过以下方式访问这些值:
e.hello;
e.world;
Run Code Online (Sandbox Code Playgroud)
如何创建enum带字符串值?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
Run Code Online (Sandbox Code Playgroud) 我在玩打字稿一点。
假设我有一个object这样的
let colors = {
RED: "r",
GREEN: "g",
BLUE: "b"
}
Run Code Online (Sandbox Code Playgroud)
现在我想把它转换成一种enum类型
enum Colors = {
RED = "r",
GREEN = "g",
BLUE = "b"
}
Run Code Online (Sandbox Code Playgroud)
更新:
我想要typings为颜色对象生成,这样如果我key向颜色对象添加另一个,它应该包含在typings.
如果我做
colors['YELLOW'] = "y"
Run Code Online (Sandbox Code Playgroud)
那么生成的typings应该是
declare enum colors {
RED = "r",
GREEN = "g",
BLUE = "b",
YELLOW = "y"
}
Run Code Online (Sandbox Code Playgroud)
相反,生成类型是
declare const colors {
[x: string]: string
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?