function stringToEnum(enumType: any, enumString: string): any { return enumType[enumString]; } const colorString = "Green"; const colorEnum = stringToEnum(Color, colorString); console.log(colorEnum); // 输出: Colo
并且您想要一个简单的具有编译时和运行时安全性的string-to-Enum转换器,下面的方法效果很好:...
可以按照以下方式实现转换函数: 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....
首先,我们定义一个Direction枚举,并为每个方向指定一个值: enumDirection{Up,Down,Left,Right,} 1. 2. 3. 4. 5. 6. 接下来,我们编写一个函数getDirectionFromString,它将用户输入的字符串转换为对应的枚举成员: functiongetDirectionFromString(str:string):Direction{switch(str.toLowerCase()){case"up":retu...
let arr2:[number, string, number] = [1,"2",3]; // 若果写成 [1,2,3] 会报错 元素是严格规定了数组的长度和每个位置的元素类型,并且在赋值时需要严格对应,否则会报错。 枚举 enum类型是对JavaScript标准数据类型的一个补充。 像C#等其它语言一样,使用枚举类型可以为一组数值赋予友好的名字。
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 ...
[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...
type CustomArray=(number|string)[]letarr1:CustomArray=[1,'a']letarr2:CustomArray=[2,'b'] 函数类型 函数的类型实际上指的是:函数参数和返回值类型。为函数指定类型的两种方式: 单独指定参数、返回值类型。 functionadd(num1:number,num2:number):number{returnnum1+num2}constadd=(num1:number,num2:nu...
enumColor{Red=1,Green,Blue}letcolorName:string=Color[2];alert(colorName);// 显示'Green'因为上面代码里它的值是2 任意值 有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。 这种情况下,我们不希望类型检查器对这些值进行检...