如何以编程方式枚举枚举类型?

编程入门 行业动态 更新时间:2024-10-26 16:27:14
本文介绍了如何以编程方式枚举枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个TypeScript 枚举, MyEnum ,如下所示:

Say I have a TypeScript enum, MyEnum, as follows:

enum MyEnum { First, Second, Third }

在TypeScript 0.9.5中生成 enum 数组的最佳方法是什么?价值观?示例:

What would be the best way in TypeScript 0.9.5 to produce an array of the enum values? Example:

var choices: MyEnum[]; // or Array<MyEnum> choices = MyEnum.GetValues(); // plans for this? choices = EnumEx.GetValues(MyEnum); // or, how to roll my own?

推荐答案

这是该枚举的JavaScript输出:

This is the JavaScript output of that enum:

var MyEnum; (function (MyEnum) { MyEnum[MyEnum["First"] = 0] = "First"; MyEnum[MyEnum["Second"] = 1] = "Second"; MyEnum[MyEnum["Third"] = 2] = "Third"; })(MyEnum || (MyEnum = {}));

哪个对象是这样的:

{ "0": "First", "1": "Second", "2": "Third", "First": 0, "Second": 1, "Third": 2 }

具有字符串值的枚举成员

TypeScript 2.4添加了枚举可能具有字符串枚举成员值的功能。因此,可能最终得到如下所示的枚举:

TypeScript 2.4 added the ability for enums to possibly have string enum member values. So it's possible to end up with an enum that look like the following:

enum MyEnum { First = "First", Second = 2, Other = "Second" } // compiles to var MyEnum; (function (MyEnum) { MyEnum["First"] = "First"; MyEnum[MyEnum["Second"] = 2] = "Second"; MyEnum["Other"] = "Second"; })(MyEnum || (MyEnum = {}));

获取会员名

我们可以看看上面的示例试图弄清楚如何获得枚举成员:

We can look at the example immediately above to try to figure out how to get the enum members:

{ "2": "Second", "First": "First", "Second": 2, "Other": "Second" }

这是我想出的内容:

const e = MyEnum as any; const names = Object.keys(e).filter(k => typeof e[k] === "number" || e[k] === k || e[e[k]]?.toString() !== k );

成员值

一旦名称,我们可以通过以下操作遍历它们以获得相应的值:

Once, we have the names, we can loop over them to get the corresponding value by doing:

const values = names.map(k => MyEnum[k]);

扩展类

我认为最好的方法为此,是创建自己的函数(例如 EnumEx.getNames(MyEnum))。您不能向枚举添加函数。

I think the best way to do this is to create your own functions (ex. EnumEx.getNames(MyEnum)). You can't add a function to an enum.

class EnumEx { private constructor() { } static getNamesAndValues(e: any) { return EnumEx.getNames(e).map(n => ({ name: n, value: e[n] as string | number })); } static getNames(e: any) { return Object.keys(e).filter(k => typeof e[k] === "number" || e[k] === k || e[e[k]]?.toString() !== k ); } static getValues(e: any) { return EnumEx.getNames(e).map(n => e[n] as string | number); } }

更多推荐

如何以编程方式枚举枚举类型?

本文发布于:2023-11-03 16:44:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!