简体   繁体   English

如何在打字稿中为数字枚举提供替代字符串定义

[英]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我期待像下面这样的枚举在 c# 中的描述属性

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:您可以将枚举字符串存储在Map对象中:

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.有关两种技术的演示,请参阅此 stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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