具有多个字符串值的打字稿枚举

Rua*_*uan 11 enums typescript

我努力找到一种方法来获取我的枚举变量名称和显示名称的字符串部分(同时使用变量名称和字符串“显示”名称)

我想要这个是因为我会在过滤器查询中使用变量名,并在前端显示显示名。

所以我找到了一种方法来创建一个对象来充当枚举,并认为 id 只是为你们添加它在这里。

Fal*_*ger 12

您可以使用带有私有构造函数的类,而不是创建接口或枚举。并创建static readonly您的类的实例。

export class RewardCategory {
  public static readonly swapPoints = new RewardCategory('swapPoints', 'Swap Points');
  public static readonly charity = new RewardCategory('charity', 'Charity');
  public static readonly discountVouchers = new RewardCategory('discountVouchers', 'Discount Vouchers');

  private constructor(public readonly variable: string, public readonly displayName: string) {
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

RewardCategory.charity.displayName
Run Code Online (Sandbox Code Playgroud)

或者

RewardCategory.charity.variable
Run Code Online (Sandbox Code Playgroud)


Rua*_*uan 8

因此,不要创建枚举,只需以这种格式创建一个对象即可。

export let RewardCategory = { 
  swapPoints:  {variable: 'swapPoints', display: 'Swap Points' },
  charity: {variable: 'charity', display: 'Charity' },
  discountVouchers: {variable: 'discountVouchers', display: 'Discount Vouchers' }
}
Run Code Online (Sandbox Code Playgroud)

然后,包括 thisEnum 布局。

export interface EnumLayout {
    variable: string;
    display: string;
}
Run Code Online (Sandbox Code Playgroud)

然后,只需像这样使用它。

 (<EnumLayout>RewardCategory['swapPoints']).display 
Run Code Online (Sandbox Code Playgroud)

或者

 (<EnumLayout>RewardCategory['swapPoints']).variable
Run Code Online (Sandbox Code Playgroud)

  • 我会使用“const”而不是“let”。您还可以将每个“RewardCategory”值声明为“EnumLayout”(不应命名为“enum”)。然后,您可以使用“RewardCategory.swapPoints.display”。 (3认同)