0

The string of an enum can be obtained as below:

enum eURL {
    projects
    }

let x:string = eURL[eURL.projects]; //x= 'projects'

However, if I use string enums as in the example below, then how can I get the string value "Help Me" from the enum?

enum myEnum {
    projects = "Help Me",
}

let x:string = myEnum[myEnum.projects]; // returns undefined.

2 Answers 2

3

You just use it directly:

let x:string = myEnum.projects;

Live copy on the TypeScript playground.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, sometimes the obvious eludes
0

The reason why first example works and second not is connected to how is typescript transpiling normal enum vs string enum. Normal:

(function (myEnum) {
    myEnum[myEnum["projects"] = 0] = "projects";
})(myEnum || (myEnum = {}));

It uses index as key and also value as key and do mapping from value to index and index to value and produce object which look like this:

{0: "projects", projects: 0}

String:

(function (myEnum) {
    myEnum["projects"] = "Help Me";
})(myEnum || (myEnum = {}));

String enum on the other hand map only key to value and produce this:

{projects: 0}

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.