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>());
}
2
  • The answer is in the other question; make n explicitly a string (DbMapNames[<string>n]). Commented Nov 3, 2017 at 11:48
  • No, at this case I get other error: TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. Commented Nov 3, 2017 at 12:00

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.