0

I have a basic errorCode enum such as

export enum SomeErrorCodes {
    none = 0,
    notFound = 1,
    duplicated = 2
}

I receive from an webAPI the name of the enum as a string "SomeErrorCodes" and a number, let's say 1. How can I parse these into SomeErrorCodes.notFound in typescript ?

Thanks

5
  • You probably need to include more details about what the response from the server is. "SomeErrorCodes" and a number isn't very clear. What does the object look like? Is it { "SomeErrorCodes": 1 } Commented Jan 4, 2019 at 18:09
  • My API is sending a keyvaluepair <string, int> so this would be {"SomeErrorCodes", 1 }. I have several error enums, so I want to get the enum out of its name, so I can do SomeErrorCodes[1] Commented Jan 7, 2019 at 9:00
  • What's the ultimate use case for these? It sounds like you may not actually want the enum itself, but a string that represents the error. If the value you're parsing could be one of several enum types, the parsed value is going to be any type, right? Commented Jan 7, 2019 at 19:51
  • The use case is to get the matching translation for errors. As for wanting the string instead of the enum, that's partially, true. My enum has flags (didn't state that to keep my question simple) so a value may, in fact, have several errors embedded. I already have methods that allow me to extract those errors, but I need the enum for that. Commented Jan 8, 2019 at 10:13
  • I updated my answer; I think it should work for you now. Commented Jan 8, 2019 at 17:39

2 Answers 2

1

Your enum will be transpiled into

Object
0: "none"
1: "notFound"
2: "duplicated"
duplicated: 2
none: 0
notFound: 1

So you can easily get a value by key,

function getErrorCode(code: number): string {
  return SomeErrorCodes[code] || 'Code not exist';
}
Sign up to request clarification or add additional context in comments.

1 Comment

The thing is I have several error enums and don´t know upfront what's the enum that's coming from the server. The server is sending a KeyValuePair<string, int> with the name of the enum as a string and the value as an int, for eg. { "SomeErrorCodes", 1 }
0

You can use Object.keys to get the key name, then use that to get the appropriate enum. This will run at https://www.typescriptlang.org/play/index.html and should give you enough to get it done:

enum Fruits {
    Apple = 1,
    Orange
}

enum Vegetables {
    Carrot = 75,
    Lettuce = 88,
    Asparagus = 96
}

class ThingParser {
    public GetArbitraryValues(fromObject: any): string[] {
        const fancyStrings: string[] = [];
        const key = Object.keys(fromObject)[0];

        let getStringMethod: (theValue: number) => string;

        switch (key) {
            case "Fruits":
                getStringMethod = (fruit: number) => {
                    return Fruits[fruit];
                }
                break;
            case "Vegetables":
                getStringMethod = (veg: number) => {
                    return Vegetables[veg];
                }
                break;
            default:
                throw "Unknown enum...";
        }

        const intValues = (<string>fromObject[key]).split(",")
            .map(x => Number.parseInt(x.trim()));


        for (const intVal of intValues) {
            fancyStrings.push(getStringMethod(intVal));
        }

        return fancyStrings;
    }
}

const parser = new ThingParser();
let fruits = document.createElement('h2');
fruits.textContent = parser.GetArbitraryValues({ "Fruits": "1,2" }).join(", ");
document.body.appendChild(fruits);
let veggies = document.createElement('h2');
veggies.textContent = parser.GetArbitraryValues({ "Vegetables": "88" }).join(", ");
document.body.appendChild(veggies);

3 Comments

The thing is I have several error enums and don´t know upfront what's the enum that's coming from the server. The server is sending a KeyValuePair<string, int> with the name of the enum as a string and the value as an int, for eg. { "SomeErrorCodes", 1 }
Well, that would be great if I received the object. enum Fruits { Apple = 1, Orange = 2 } enum Vegetables { Carrot = 1, Lettuce = 2, Asparagus = 3 } What I receive would be {"Fruits", 2 }
That is correct. That is a JSON object. "Fruits" is the first object key. Object.keys(x)[0]; will get the first key. Pass the whole object, { "Fruits", 2 } into that method to get the key name.

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.