我在TypeScript中定义了以下enum:

enum Color{
    Red, Green
}

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

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

如何将该值转换为enum?


当前回答

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

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

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 2.1开始,enum中的字符串键都是强类型的。Keyof typeof用于获取可用字符串键的信息(1):

enum Color{
    Red, Green
}

let typedColor: Color = Color.Green;
let typedColorString: keyof typeof Color = "Green";

// Error "Black is not assignable ..." (indexing using Color["Black"] will return undefined runtime)
typedColorString = "Black";

// Error "Type 'string' is not assignable ..." (indexing works runtime)
let letColorString = "Red";
typedColorString = letColorString;

// Works fine
typedColorString = "Red";

// Works fine
const constColorString = "Red";
typedColorString = constColorString

// Works fine (thanks @SergeyT)
let letColorString = "Red";
typedColorString = letColorString as keyof typeof Color;

typedColor = Color[typedColorString];

https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

我需要知道如何循环枚举值(正在测试许多排列的几个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/

其他的变化可以是

const green= "Green";

const color : Color = Color[green] as Color;

打印稿1.倍

如果你确定输入字符串与Color enum完全匹配,那么使用:

const color: Color = (<any>Color)["Red"];

在输入字符串可能不匹配Enum的情况下,使用:

const mayBeColor: Color | undefined = (<any>Color)["WrongInput"];
if (mayBeColor !== undefined){
     // TypeScript will understand that mayBeColor is of type Color here
}

操场上


如果我们没有将enum转换为<任意>类型,那么TypeScript将显示错误:

元素隐式具有“any”类型,因为索引表达式不是类型“number”。

这意味着默认情况下,TypeScript Enum类型与数字索引一起工作。 let c = Color[0],但是没有像let c = Color["string"]这样的字符串索引。这是微软团队针对更一般问题对象字符串索引的一个已知限制。

2.打印稿x-4x

TypeScript移动到typeof概念的键。

如果some使用字符串值enum:

enum Color {
  Green = "GRN",
  Red = "RD"
}

然后有语言解决方案映射键值(颜色。Green -> "GRN")只是通过访问枚举成员,但没有简单的方法来做相反的事情("GRN" -> Color.Green)。通过使用反向映射:

请记住,字符串enum成员不会得到反向映射 根本就不存在。

一种可能的解决方案是手动检查值并将值强制转换为enum。请注意,它只适用于字符串枚举。

function enumFromStringValue<T> (enm: { [s: string]: T}, value: string): T | undefined {
  return (Object.values(enm) as unknown as string[]).includes(value)
    ? value as unknown as T
    : undefined;
}

enumFromStringValue(Color, "RD"); // Color.Red
enumFromStringValue(Color, "UNKNOWN"); // undefined
enumFromStringValue(Color, "Red"); // undefined

如果TypeScript编译器知道变量的类型是字符串,那么这是可行的:

let colorName : string = "Green";
let color : Color = Color[colorName];

否则,你应该显式地将其转换为字符串(以避免编译器警告):

let colorName : any = "Green";
let color : Color = Color["" + colorName];

在运行时,两个解决方案都可以工作。