如何将字符串转换为枚举?
我之前看过this主题并尝试使用该答案,但它在我的代码中不起作用(我评论了错误消息):
type ID = string;
export enum DbMapNames{
Document,
Level,
Node,
Condition,
Reference,
Connection
}
let map = new Map<DbMapNames, Map<ID, any>>(); // the map of the maps.
for(let n in DbMapNames){
// TS2345: Argument of type 'string' is not assignable to parameter of type 'DbMapNames'
if(!map.has(DbMapNames[n])) map.set(DbMapNames[n], new Map<ID, any>());
}
1 回答
您在循环中获得的键包括所有名称和所有数字,因此您将看到找到的字符串值:
因此,您可以选择使用原始数字,名称或任何您喜欢的内容 .
下面的代码只使用数字0到5并获取数值
num
,枚举en
和字符串名称name
.输出: