确定枚举元素的数量 TypeScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38034673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:35:57  来源:igfitidea点击:

Determine the number of enum elements TypeScript

typescriptenums

提问by TheMuffinCoder

As said in the title, how can you determine the number of elements in a enum in Typescript such as in this example

如标题所述,如何确定 Typescript 中枚举中的元素数量,例如在此示例中

enum ExampleEnum {

    element1 = 1,
    element2 = 2,
    element3 = 3,
    element4 = 4,
    element5 = 5,
    element6 = 6

}

var exampleEnumElementCount:number = ? 

How would the count be determined? In this case it should be 6

如何确定计数?在这种情况下,它应该是 6

回答by Zen

Typescript does not provide a standard method to get the number of enum elements. But given the the implementationof enum reverse mapping, the following works:

Typescript 不提供获取枚举元素数量的标准方法。但考虑到实施枚举反向映射,以下工作:

Object.keys(ExampleEnum).length / 2

Note, for string enumsyou do notdivide by zero as no reverse mapping properties are generated:

请注意,对于字符串枚举,不能除以零,因为不会生成反向映射属性:

Object.keys(StringEnum).length;

Enums with mixed strings and numeric values can be calculated by:

具有混合字符串和数值的枚举可以通过以下方式计算:

Object.keys(ExampleEnum).filter(isNaN).length

回答by steabert

If you have an enum with numbers that counts from 0, you can insert a placeholder for the size as last element, like so:

如果您有一个从 开始计数的枚举0,您可以插入一个占位符作为大小的占位符作为最后一个元素,如下所示:

enum ERROR {
  UNKNOWN = 0,
  INVALID_TYPE,
  BAD_ADDRESS,
  ...,
  __LENGTH
}

Then using ERROR.__LENGTHwill be the size of the enum, no matter how many elements you insert.

然后使用ERROR.__LENGTH将是枚举的大小,无论您插入多少个元素。

For an arbitrary offset, you can keep track of it:

对于任意偏移量,您可以跟踪它:

enum ERROR {
  __START = 7,
  INVALID_TYPE,
  BAD_ADDRESS,
  __LENGTH
}

in which case the amount of meaningful errors would be ERROR.__LENGTH - (ERROR.__START + 1)

在这种情况下,有意义的错误数量将是 ERROR.__LENGTH - (ERROR.__START + 1)

回答by Esqarrouth

The accepted answer doesn't work in any enum versions that have a value attached to them. It only works with the most basic enums. Here is my version that works in all types:

接受的答案不适用于任何附加了值的枚举版本。它只适用于最基本的枚举。这是我适用于所有类型的版本:

export function enumElementCount(enumName: any): number {
    let count = 0
    for(let item in enumName) {
        if(isNaN(Number(item))) count++
    }
    return count
}

Here is test code for mocha:

下面是 mocha 的测试代码:

it('enumElementCounts', function() {
    enum IntEnum { one, two }
    enum StringEnum { one = 'oneman', two = 'twoman', three = 'threeman' }
    enum NumberEnum { lol = 3, mom = 4, kok = 5, pop = 6 }
    expect(enumElementCount(IntEnum)).to.equal(2)
    expect(enumElementCount(StringEnum)).to.equal(3)
    expect(enumElementCount(NumberEnum)).to.equal(4)
})

回答by sme

To further expand on @Esqarrouth's answer, each value in an enum will produce two keys, except for string enum values. For example, given the following enum in TypeScript:

为了进一步扩展@Esqarrouth 的答案,枚举中的每个值都将生成两个键,字符串枚举值除外。例如,给定以下 TypeScript 枚举:

enum MyEnum {
    a = 0, 
    b = 1.5,
    c = "oooo",
    d = 2,
    e = "baaaabb"
}

After transpiling into Javascript, you will end up with:

转译成 Javascript 后,您将得到:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["a"] = 0] = "a";
    MyEnum[MyEnum["b"] = 1.5] = "b";
    MyEnum["c"] = "oooo";
    MyEnum[MyEnum["d"] = 2] = "d";
    MyEnum["e"] = "baaaabb";
})(MyEnum || (MyEnum = {}));

As you can see, if we simply had an enum with an entry of agiven a value of 0, you end up with two keys; MyEnum["a"]and MyEnum[0]. String values on the other hand, simply produce one key, as seen with entries cand eabove.

如您所见,如果我们只是有一个条目 的枚举,a给定的值为0,那么您最终会得到两个键;MyEnum["a"]MyEnum[0]。另一方面,字符串值只生成一个键,如条目ce以上所示。

Therefore, you can determine the actual count by determining how many Keys are not numbers; ie,

因此,您可以通过确定有多少 Key 不是数字来确定实际数量;IE,

var MyEnumCount = Object.keys(MyEnum).map((val, idx) => Number(isNaN(Number(val)))).reduce((a, b) => a + b, 0);

It simply maps through all keys, returning 1if the key is a string, 0otherwise, and then adds them using the reduce function.

它只是映射所有键,1如果键是字符串则返回,0否则返回,然后使用 reduce 函数添加它们。

Or, a slightly more easier to understand method:

或者,一个更容易理解的方法:

var MyEnumCount = (() => {
    let count = 0;
    Object.keys(MyEnum).forEach((val, idx) => {
        if (Number(isNaN(Number(val)))) {
            count++;
        }
    });
    return count;
})();

You can test for yourself on the TypeScript playground https://www.typescriptlang.org/play/

您可以在 TypeScript 游乐场https://www.typescriptlang.org/play/上亲自测试