function stringToEnum(enumType: any, enumString: string): any { return enumType[enumString]; } const colorString = "Green"; const colorEnum = stringToEnum(Color, colorString); console.log(colorEnum); // 输出: Color.Green 处理未定义的情况:如果传入的字符串值在枚举中不存在,上述代码将返回...
可以按照以下方式实现转换函数: functionstringToEnumValue<T>(value:string,enumType:T):T[keyofT]|undefined{constenumValues=Object.values(enumType);for(constenumValueofenumValues){if(typeofenumValue==="string"&&enumValue.toLowerCase()===value.toLowerCase()){returnenumValue;}}returnundefined;} 1....
下面是一个示例的优化对比代码: // 优化前functionhandleString(value:string):string{returnvalue.toLowerCase();}// 优化后functionhandleString(value:string):string{return(valueasstring).toLowerCase();} 1. 2. 3. 4. 5. 6. 7. 8. 9. 定制开发 在实现字符串转枚举的过程时,定制化开发是常见的需求。
并且您想要一个简单的具有编译时和运行时安全性的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....
function getLocalizedStatusText(status: Status, lang: 'en' | 'zh'): string { const map = lang === 'en' ? statusTextMapEN : statusTextMapZH; return map[status] || 'Unknown'; } 5. 无法扩展自定义属性 如果需要为枚举项添加额外属性(如图标、颜色、权限等),原生 enum 无法满足: ...
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 ...
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...