可以按照以下方式实现转换函数: functionstringToEnumValue<T>(value:string,enumType:T):T[keyofT]|undefined{constenumValues=Object.values(enumType);for(constenumValueofenumValues){if(typeofenumValue==="string"&&enumValue.to
function stringToEnum(enumType: any, enumString: string): any { return enumType[enumString]; } const colorString = "Green"; const colorEnum = stringToEnum(Color, colorString); console.log(colorEnum); // 输出: Color.Green 处理未定义的情况:如果传入的字符串值在枚举中不存在,上述代码将返回...
enumDirection{Up,Down,Left,Right,} 1. 2. 3. 4. 5. 6. 接下来,我们编写一个函数getDirectionFromString,它将用户输入的字符串转换为对应的枚举成员: functiongetDirectionFromString(str:string):Direction{switch(str.toLowerCase()){case"up":returnDirection.Up;case"down":returnDirection.Down;case"left...
并且您想要一个简单的具有编译时和运行时安全性的string-to-Enum转换器,下面的方法效果很好:...
enum Color{ Red, Green } 现在在我的函数中,我将颜色作为字符串接收。我尝试了以下代码: var green= "Green"; var color : Color = <Color>green; // Error: can't convert string to enum 如何将该值转换为枚举? 原文由 Amitabh 发布,翻译遵循 CC BY-SA 4.0 许可协议 type...
问如何在TypeScript中将字符串转换为枚举?EN在应用程序中,我们经常需要将日期字符串转换为日期对象。在...
[TypeScript] String Enums and Inlining Members enum Sizes { Small= "small", Medium= "medium", Large= "large"} letselected: Sizes=Sizes.Samll;functionupdateSize(size: Sizes):void{ selected=size; } updateSize(Sizes.large); Interesting thing is that you can use enum as Type....
String enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself. 自增而来的失去了可读性,所以不支持自增。同理,字符串枚举值本就可读,不再需要反向映射: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 var Direction; (fun...
enumColor{Red=1,Green,Blue}letcolorName:string=Color[2];alert(colorName);// 显示'Green'因为上面代码里它的值是2 任意值 有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。 这种情况下,我们不希望类型检查器对这些值进行检...
As of TypeScript 2.4, it is now possible to define string enums, or more precisely, enums with string members. Just like any other numeric enum, string enums can be made constant using theconstmodifier so that they disappear entirely from the generated JavaScript; in this case, all enum ...