如何在 TypeScript 中将字符串转换为枚举?

如何在 TypeScript 中将字符串转换为枚举?

问题描述:

我在 TypeScript 中定义了以下枚举:

I have defined the following enum in TypeScript:

enum Color{
    Red, Green
}

现在在我的函数中,我将颜色作为字符串接收.我尝试了以下代码:

Now in my function I receive color as a string. I have tried the following code:

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

如何将该值转换为枚举?

How can I convert that value to an enum?

TypeScript 0.9 中的枚举是基于字符串+数字的.简单的转换不需要类型断言:

Enums in TypeScript 0.9 are string+number based. You should not need type assertion for simple conversions:

enum Color{
    Red, Green
}

// To String
 var green: string = Color[Color.Green];

// To Enum / number
var color : Color = Color[green];

在线试用

我在我的 OSS 书中有关于这个和其他枚举模式的文档:https://basarat.gitbook.io/typescript/type-system/enums

I have documention about this and other Enum patterns in my OSS book : https://basarat.gitbook.io/typescript/type-system/enums