简体   繁体   中英

How to have alternative string definition for numeric enum in typescript

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM