我在TypeScript中定义了以下enum:

enum Color{
    Red, Green
}

现在在我的函数中,我以字符串的形式接收颜色。我尝试了以下代码:

var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum

如何将该值转换为enum?


当前回答

试试这个

var color: color =(任何颜色)["绿色];

这对于3.5.3版本来说很好

其他回答

这些答案对我来说都太复杂了……

您可以简单地在枚举上创建一个解析函数,期望其中一个键作为参数。添加新颜色时,不需要进行其他更改

enum Color { red, green}

// Get the keys 'red' | 'green' (but not 'parse')
type ColorKey = keyof Omit<typeof Color, 'parse'>;

namespace Color {
  export function parse(colorName: ColorKey ) {
    return Color[colorName];
  }
}

// The key 'red' exists as an enum so no warning is given
Color.parse('red');  // == Colors.red

// Without the 'any' cast you would get a compile-time warning
// Because 'foo' is not one of the keys in the enum
Color.parse('foo' as any); // == undefined

// Creates warning:
// "Argument of type '"bar"' is not assignable to parameter of type '"red" | "green"'"
Color.parse('bar');

试试这个

var color: color =(任何颜色)["绿色];

这对于3.5.3版本来说很好

这个笔记与basarat的回答有关,而不是最初的问题。

我在自己的项目中遇到了一个奇怪的问题,编译器给出了一个大致相当于“不能将字符串转换为颜色”的错误,使用这段代码的等价物:

var colorId = myOtherObject.colorId; // value "Green";
var color: Color = <Color>Color[colorId]; // TSC error here: Cannot convert string to Color.

我发现编译器的类型推断变得混乱,它认为colorId是一个enum值,而不是一个ID。为了解决这个问题,我必须将ID转换为字符串:

var colorId = <string>myOtherObject.colorId; // Force string value here
var color: Color = Color[colorId]; // Fixes lookup here.

我不确定是什么导致了这个问题,但我会在这里留下这张便条,以防有人遇到和我一样的问题。

如果你正在处理TypeScript 4.1+和字符串enum,并且你想要一个简单的具有编译时和运行时安全的字符串到enum转换器,下面的工作很好:

export const asEnum = <
  T extends { [key: string]: string },
  K extends keyof T & string
>(
  enumObject: T,
  value: `${T[K]}`
): T[K] => {
  if (Object.values(enumObject).includes(value)) {
    return (value as unknown) as T[K];
  } else {
    throw new Error('Value provided was not found in Enum');
  }
};

enum Test {
  hey = 'HEY',
}

const test1 = asEnum(Test, 'HEY');   // no complaints here
const test2 = asEnum(Test, 'HE');    // compile-time error
const test3 = asEnum(Test, 'HE' as any); // run-time error

我需要知道如何循环枚举值(正在测试许多排列的几个enum),我发现这工作得很好:

export enum Environment {
    Prod = "http://asdf.com",
    Stage = "http://asdf1234.com",
    Test = "http://asdfasdf.example.com"
}

Object.keys(Environment).forEach((environmentKeyValue) => {
    const env = Environment[environmentKeyValue as keyof typeof Environment]
    // env is now equivalent to Environment.Prod, Environment.Stage, or Environment.Test
}

来源:https://blog.mikeski.net/development/javascript/typescript-enums-to-from-string/