TypeScript:如何将字符串转换为枚举?

时间:2017-11-03 11:42:52

标签: typescript

如何将字符串转换为枚举?

之前我查看了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 :(得分:1)

您在循环中获得的键包括所有名称和所有数字,因此您将看到找到的字符串值:

0,1,2,3,4,5,Document,Level,Node,Condition,Reference,Connection

因此,您可以选择使用原始数字,名称或任何您喜欢的内容。

下面的代码只使用数字0到5并获取数值num,枚举en和字符串名称name

enum DbMapNames{
    Document,
    Level,
    Node,
    Condition,
    Reference,
    Connection
}

for (let n in DbMapNames) {
    const num = parseInt(n, 10);

    if (isNaN(num)) {
        // this is Document, Level, Node, Condition, Reference, Connection
        continue;
    }

    // Enum, i.e. DbMapNames.Level
    const en: DbMapNames = num;

    // String Name, i.e. Level
    const name = DbMapNames[n];

    console.log(n, num, en, name);
}

输出:

0 0 0 Document
1 1 1 Level
2 2 2 Node
3 3 3 Condition
4 4 4 Reference
5 5 5 Connection