我有一个如下的数字枚举。
enum Rating {
Unknown = 0,
One,
Two,
Three,
Four
}
当我访问如下所示的枚举字符串时,我需要获取枚举的备用字符串值。
var stringVal = Rating[Rating.One];
以上一行应该给我“ Rate of One”(而不是One)。
我需要坚持使用数字枚举,并且不能使用字符串枚举。一旦解决,我想到的就是使用如下所示的字符串数组。
const stringRating = ["Unknown Rating", "Rating One", "Rating is Two", "Rating is Three", "Rating is Four"];
export function toString(rating: Rating): string {
return stringValues[rating];
但是有没有更好的方法可以在打字稿中实现呢?
我期望像下面的枚举那样在c#中使用诸如Description属性之类的东西
public enum MyEnum
{
[Description("value 1")]
Value1,
[Description("value 2")]
Value2,
[Description("value 3")]
Value3
}
答案 0 :(得分:1)
您可以将枚举字符串存储在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);
...
}
或者,如果所有枚举值的字符串格式都相同,则可以使用如下函数:
ratingToString(rating: Rating): string {
return `Rating ${Rating[rating]}`;
}
doSomething() {
let str = this.ratingToString(Rating.Unknown);
...
}
有关这两种技术的演示,请参见this stackblitz。