1

How to convert the string to the enum?

I looked this theme before and try to use that answer but it doesn't work in mine code (I commented the error message):

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>());
}
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

1 Answers1

1

The keys you get in your loop include all of the names, and all of the numbers, so you'll see string values being found for:

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

So you can choose to work with the raw numbers, or the names, or whatever you like.

The code below just uses the numbers 0 to 5 and gets the numeric value num, the enum en, and the string name 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);
}

Output:

0 0 0 Document
1 1 1 Level
2 2 2 Node
3 3 3 Condition
4 4 4 Reference
5 5 5 Connection
Fenton
  • 241,084
  • 71
  • 387
  • 401