1

I have a numeric enum like below.

enum Rating {
  Unknown = 0,
  One,
  Two,
  Three,
  Four
}

I need to get alternative string value of enum when I access the enum string like below.

var stringVal = Rating[Rating.One];

The above line should give me "Rating of One" instead of One.

I need to stick to numeric enums and cannot use string enums. Once solution what I could think of is to use string array like below.

const stringRating = ["Unknown Rating", "Rating One", "Rating is Two", "Rating is Three", "Rating is Four"];
export function toString(rating: Rating): string {
return stringValues[rating];

But is there a better way to achieve this in typescript?

I'm expecting something like Description attribute in c# for enums like below

public enum MyEnum 
{ 
  [Description("value 1")] 
  Value1, 
  [Description("value 2")]
  Value2, 
  [Description("value 3")]
  Value3
}

1 Answer 1

1

You could store the enum strings in a Map object:

ratingStrings = new Map<Rating,string>([
  [Rating.Unknown, "Unknown Rating"],
  [Rating.One, "Rating One"],
  [Rating.Two, "Rating is Two"],
  [Rating.Three, "Rating is Three"],
  [Rating.Four, "Rating is Four"],
]);

doSomething() {
  let str = this.ratingStrings.get(Rating.Unknown);
  ...
}

Alternatively, in cases where the string format is the same for all enum values, you could use a function like the following:

ratingToString(rating: Rating): string {
  return `Rating ${Rating[rating]}`;
}

doSomething() {
  let str = this.ratingToString(Rating.Unknown);
  ...
}

See this stackblitz for a demo of both techniques.

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.