首页 文章

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

提问于
浏览
1

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

我之前看过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 回答

  • 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
    

相关问题