相关疑难解决方法(0)

使用字符串值创建枚举

以下代码可用于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)

typescript

241
推荐指数
12
解决办法
18万
查看次数

在Typescript中将字符串数组转换为枚举

我在玩打字稿一点。

假设我有一个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)

我怎样才能做到这一点?

arrays enums types object typescript

9
推荐指数
1
解决办法
9142
查看次数

标签 统计

typescript ×2

arrays ×1

enums ×1

object ×1

types ×1