typescript function stringToEnum(enumType: any, enumString: string): any { return enumType[enumString]; } const colorString = "Green"; const colorEnum = stringToEnum(Color, colorString); console.log(colorEnum);
可以按照以下方式实现转换函数: 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....
在TypeScript中,可以使用枚举的[枚举名][字符串]语法来获取对应的枚举成员。下面是一个简单的示例: enumDirection{Up,Down,Left,Right,}functiongetDirectionFromString(str:string):Direction{returnDirection[str];}constdirection=getDirectionFromString("Up");console.log(direction);// 输出:0 1. 2. 3. 4. ...
问TypeScript:当尝试访问Enum时,没有带有“string”类型参数的索引签名EN本章节要介绍的内容为 TS 接口...
Interesting thing is that you can use enum as Type. This is what compile to Javscript: But if you add 'const' to enum: const enum Sizes { Small= "small", Medium= "medium", Large= "large" } It compiles to such smaller amount code, with only necessary information...
问在Array<string>中将Record<Enum>转换为TypeScriptEN正如@captain正确地指出的那样,您不能使用map,...
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 ...
See this comment on the original pull request which brought string enums to Typescript. Also mentioned in that thread was the syntax of enum<T = number> to describe enums. I think this syntax works quite nicely. So for strings we might have: enum<string> TaskIds { TASK_RESIZE_IMAGE, ...
A string enum is inferred by looking at the constant value of the initializer of its first member: enum stringsInferred { a = "a", b, // "b" c // "c" } Or it is declared using a string index: enum stringsDeclared { [prop: string] : strin...
最常见的基本类型就是布尔类型了,其值就是 true 或者 false,类型声明用 boolean 就好了,在 TypeScript 中,声明一个 boolean 类型的变量写法如下: let isDone: boolean = false; console.log(isDone, typeof isDone); 这里注意到,声明类型可以在变量名的后面加上一个冒号,然后跟一个类型声明,和 Python 的 Type...