【发布时间】:2018-09-06 09:31:20
【问题描述】:
我很难找到一种方法来获取我的枚举变量名称和显示名称的字符串部分(同时使用变量名称和字符串“显示”名称)
我想要这个是因为我会在过滤器查询中使用变量名,并在前端显示显示名称。
所以我找到了一种方法来创建一个对象来充当枚举,并认为 id 只需将它添加到这里就可以了。
【问题讨论】:
标签: typescript enums
我很难找到一种方法来获取我的枚举变量名称和显示名称的字符串部分(同时使用变量名称和字符串“显示”名称)
我想要这个是因为我会在过滤器查询中使用变量名,并在前端显示显示名称。
所以我找到了一种方法来创建一个对象来充当枚举,并认为 id 只需将它添加到这里就可以了。
【问题讨论】:
标签: typescript enums
您可以使用带有私有构造函数的类,而不是创建接口或枚举。并为您的班级创建 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
【讨论】:
所以不要创建一个枚举,而是创建一个这种格式的对象。
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。您也可以声明每个RewardCategory 值as EnumLayout(不应命名为“枚举”)。然后,您可以使用RewardCategory.swapPoints.display。
枚举被编码为纯 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
}
【讨论】: