我在TypeScript中定义了以下enum:

enum Color{
    Red, Green
}

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

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

如何将该值转换为enum?


当前回答

我得到了它的工作使用以下代码。

var green= "Green";
var color : Color= <Color>Color[green];

其他回答

在这个问题中有很多混合信息,所以让我们讨论TypeScript 2的整个实现。在Nick's Guide to Using Enums in Models with TypeScript中的x+。

本指南适用于:创建客户端代码的人,这些客户端代码从服务器获取一组已知字符串,这些字符串可以方便地在客户端建模为Enum。

定义枚举

让我们从枚举开始。它应该看起来像这样:

export enum IssueType {
  REPS = 'REPS',
  FETCH = 'FETCH',
  ACTION = 'ACTION',
  UNKNOWN = 'UNKNOWN',
}

这里需要注意两点:

我们显式地将这些声明为字符串支持的枚举情况,这允许我们用字符串来实例化它们,而不是其他一些不相关的数字。 我们添加了一个选项UNKNOWN,这个选项在我们的服务器模型上可能存在,也可能不存在。如果您愿意,可以将其处理为未定义,但我喜欢尽可能避免在类型上使用|未定义以简化处理。

使用UNKNOWN大小写的好处是,你可以在代码中非常明显地看到它,并为未知枚举大小写设置亮红色和闪烁的样式,这样你就知道你没有正确地处理某些事情。

解析枚举

您可以在另一个模型中使用这个枚举,或者单独使用这个枚举,但是您必须将字符串-y类型的枚举从JSON或XML (ha)解析为强类型的对应对象。当嵌入到另一个模型中时,这个解析器存在于类构造函数中。

parseIssueType(typeString: string): IssueType {
  const type = IssueType[typeString];
  if (type === undefined) {
    return IssueType.UNKNOWN;
  }

  return type;
}

如果枚举被正确地解析,它将以正确的类型结束。否则,它将是未定义的,您可以拦截它并返回UNKNOWN情况。如果您更喜欢使用undefined作为未知情况,则可以直接返回尝试的enum解析的任何结果。

从这里开始,只需要使用parse函数和使用新创建的强类型变量。

const strongIssueType: IssueType = parseIssueType('ACTION');
// IssueType.ACTION
const wrongIssueType: IssueType = parseIssueType('UNEXPECTED');
// IssueType.UNKNOWN

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

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

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');

它在TypeScript 4.4.3 TS游乐场链接中为我工作。

  const stringToEnumValue = <T extends Record<string, string>, K extends keyof T>(
    enumObj: T,
    value: string,
  ): T[keyof T] | undefined =>
    enumObj[
      Object.keys(enumObj).filter(
        (k) => enumObj[k as K].toString() === value,
      )[0] as keyof typeof enumObj
    ];

  enum Color {
    Red = 'red',
    Green = 'green',
  }

  const result1 = stringToEnumValue(Color, 'yellow'); // undefined
  const result2 = stringToEnumValue(Color, 'green'); // Color.Green

  console.log(result1) // undefined = undefined
  console.log(result2) // Color.Green = "green"

我得到了它的工作使用以下代码。

var green= "Green";
var color : Color= <Color>Color[green];

简单的方法

enum Color { Red, Green }

const c1 = Color["Red"]
const redStr = "Red" // important: use `const`, not mutable `let`
const c2 = Color[redStr]

这既适用于数值枚举,也适用于字符串枚举。不需要使用类型断言。

未知enum字符串

Simple, unsafe variant
const redStrWide: string = "Red" // wide, unspecific typed string
const c3 = Color[redStrWide as keyof typeof Color]
Safe variant with checks
const isEnumName = <T>(str: string, _enum: T): str is Extract<keyof T, string> =>
    str in _enum
const enumFromName = <T>(name: string, _enum: T) => {
    if (!isEnumName(name, _enum)) throw Error() // here fail fast as an example
    return _enum[name]
}
const c4 = enumFromName(redStrWide, Color)

转换字符串enum值

字符串枚举没有反向映射(与数字枚举相反)。我们可以创建一个查找助手来将枚举值字符串转换为枚举类型:

enum ColorStr { Red = "red", Green = "green" }

const c5_by_name = ColorStr["Red"] // ✅ this works
const c5_by_value_error = ColorStr["red"] // ❌ , but this not

const enumFromValue = <T extends Record<string, string>>(val: string, _enum: T) => {
    const enumName = (Object.keys(_enum) as Array<keyof T>).find(k => _enum[k] === val)
    if (!enumName) throw Error() // here fail fast as an example
    return _enum[enumName]
}

const c5 = enumFromValue("red", ColorStr)

操场上的样品