如何在 TypeScript 中将字符串转换为枚举? [英] How do I convert a string to enum in 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
这篇关于如何在 TypeScript 中将字符串转换为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文