具有多个字符串值的Typescript枚举
我努力找到一种方法来获取我的enum变量名和显示名的字符串部分(同时使用变量名和字符串“display”名) 我之所以希望这样做,是因为我会在过滤器查询中使用变量名,并在前端显示显示名称具有多个字符串值的Typescript枚举,typescript,enums,Typescript,Enums,我努力找到一种方法来获取我的enum变量名和显示名的字符串部分(同时使用变量名和字符串“display”名) 我之所以希望这样做,是因为我会在过滤器查询中使用变量名,并在前端显示显示名称 所以我找到了一种方法来创建一个对象作为枚举,我想我只需要在这里为你们添加它。所以不要创建枚举,只需要创建一个这种格式的对象 export let RewardCategory = { swapPoints: {variable: 'swapPoints', display: 'Swap Points'
所以我找到了一种方法来创建一个对象作为枚举,我想我只需要在这里为你们添加它。所以不要创建枚举,只需要创建一个这种格式的对象
export let RewardCategory = {
swapPoints: {variable: 'swapPoints', display: 'Swap Points' },
charity: {variable: 'charity', display: 'Charity' },
discountVouchers: {variable: 'discountVouchers', display: 'Discount Vouchers' }
}
然后,包含此枚举布局
export interface EnumLayout {
variable: string;
display: string;
}
然后,像这样简单地使用它
(<EnumLayout>RewardCategory['swapPoints']).display
(奖励类别['swapPoints'])。显示
或
(报酬类别['swapPoints'])。变量
枚举被编码为普通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
}
您可以使用带有私有构造函数的类,而不是创建接口或枚举。并创建类的
静态只读
实例
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
或
这是因为它更容易消费。我会使用
const
而不是let
。您还可以将每个报酬类别
值声明为EnumLayout
(不应命名为“enum”)。然后,您可以只使用RewardCategory.swapPoints.display
。
RewardCategory.charity.displayName
RewardCategory.charity.variable