(enumType: any, enumString: string): any { const result = enumType[enumString]; if (result === undefined) { throw new Error(`No enum member with value ${enumString}`); } return result; } try { const colorString = "Yellow"; const colorEnum = stringToEnum(Color, colorString); ...
下面是一个示例的优化对比代码: // 优化前functionhandleString(value:string):string{returnvalue.toLowerCase();}// 优化后functionhandleString(value:string):string{return(valueasstring).toLowerCase();} 1. 2. 3. 4. 5. 6. 7. 8. 9. 定制开发 在实现字符串转枚举的过程时,定制化开发是常见的需求。
可以按照以下方式实现转换函数: 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....
并且您想要一个简单的具有编译时和运行时安全性的string-to-Enum转换器,下面的方法效果很好:...
问如何在TypeScript中将字符串转换为枚举?EN在应用程序中,我们经常需要将日期字符串转换为日期对象。在...
function getLocalizedStatusText(status: Status, lang: 'en' | 'zh'): string { const map = lang === 'en' ? statusTextMapEN : statusTextMapZH; return map[status] || 'Unknown'; } 5. 无法扩展自定义属性 如果需要为枚举项添加额外属性(如图标、颜色、权限等),原生 enum 无法满足: ...
贰❀ 解决Enum枚举值不能是对象 我们知道ts中的类型其实可以分为比较抽象的原始类型,以及较为具体的字面量类型,比如我希望变量a的值一定是个字符串,这里就能用抽象的string表示: consta:string='1'; 此时a的值就必须是个字符串。而有时候我们希望某个变量的值,是按照我们预设好的值其一,这里就可以用联合类型...
Enum.isType(enum, value) Enum.isTypechecks if a value is of a given enum type and can be used as a type guard. For example: constColor=Enum("BLACK","WHITE"); type Color=Enum<typeofColor>; letselectedColor:Color; constcolorString=getUserInputString();//Unsanitized string. ...
enumColor{Red=1,Green,Blue}letcolorName:string=Color[2];alert(colorName);// 显示'Green'因为上面代码里它的值是2 任意值 有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。 这种情况下,我们不希望类型检查器对这些值进行检...
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...