【问题标题】:Typescript enum with multiple string values具有多个字符串值的打字稿枚举
【发布时间】:2018-09-06 09:31:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    您可以使用带有私有构造函数的类,而不是创建接口或枚举。并为您的班级创建 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) {
      }
    }
    

    那么你可以这样使用它:

    RewardCategory.charity.displayName
    

    RewardCategory.charity.variable
    

    【讨论】:

    • 赞成这个,因为它更容易消费。
    【解决方案2】:

    所以不要创建一个枚举,而是创建一个这种格式的对象。

    export const RewardCategory = { 
      swapPoints:  {variable: 'swapPoints', display: 'Swap Points' },
      charity: {variable: 'charity', display: 'Charity' },
      discountVouchers: {variable: 'discountVouchers', display: 'Discount Vouchers' }
    }
    

    那么,就这样简单的使用吧。

    RewardCategory.swapPoints.display 
    

     RewardCategory.swapPoints.variable
    

    【讨论】:

    • 我会使用const 而不是let。您也可以声明每个RewardCategoryas EnumLayout(不应命名为“枚举”)。然后,您可以使用RewardCategory.swapPoints.display
    【解决方案3】:

    枚举被编码为纯 javascript 对象,因此您可以执行以下操作:

    enum Numbers {
        one = 'number one',
        two = 'the second number'
    }
    
    for (const key in Numbers)
        console.log(`key: ${key}, value: ${Numbers[key]}`);
    
    function getTheKeyFromTheValue(value: string) {
        for (const key in Numbers)
            if (Numbers[key] === value)
                return key;
    
        return undefined; // Couldn't find it
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2018-10-23
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2022-06-11
      相关资源
      最近更新 更多