本文共 2543 字,大约阅读时间需要 8 分钟。
typescript 枚举
This is the second post on declaration merging in TypeScript. In the , we looked at what declaration merging is and started with interfaces. In this post, we will look at how to merge enums.
这是有关TypeScript中声明合并的第二篇文章。 在上 ,我们研究了声明合并是什么,并从接口开始。 在本文中,我们将研究如何合并枚举。
For an introduction to Enums and why they are useful, you can .
有关Enums以及它们为什么有用的介绍,您可以 。
Let’s get started:
让我们开始吧:
enum Department { IT, Marketing}enum Department { HR}
In our code above, since both enums have the same name, Department
, TypeScript should be able to merge them, right? Well, not so fast! This will actually throw an error in the second enum declaration if we are to leave it like this. The error reads: In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.
在上面的代码中,由于两个枚举都具有相同的名称Department
,所以TypeScript应该能够合并它们,对吗? 好吧,不是那么快! 如果我们要这样保留它,实际上将在第二个枚举声明中引发错误。 错误显示为: In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.
What this means is that, enum elements are automatically assigned values if not specified. So IT
in the first Department
enum is assigned the value 0
and Marketing
is assigned the value of 1
. In the second Department
, since HR
is the first element in that enum, it is also assigned the value of 0
. When merged, both IT
and HR
will have a value of 0
and that is not permitted hence, the error.
这意味着,如果未指定枚举元素,则会自动为其分配值。 因此,第一个Department
枚举中的IT
分配值为0
, Marketing
分配值为1
。 在第二个Department
,由于HR
是该枚举中的第一个元素,因此它也被赋值为0
。 合并后, IT
和HR
的值均为0
,因此不允许该错误。
To solve this, we can specify a value for the first element in our enum. Subsequent elements in the enum will have their values increased by one if not specified.
为了解决这个问题,我们可以为枚举中的第一个元素指定一个值。 如果未指定,则枚举中的后续元素的值将增加一。
enum Department { IT = 1, Marketing // has a value of 2, that is 1 + (IT value)}enum Department { HR // has an automatically assigned value of 0}console.log(Department[1]) // ITconsole.log(Department[2]) // Marketingconsole.log(Department[0]) // HR
By specifying the value of 1
to IT
, when HR is automatically assigned the value of 0
, it won’t cause any error because no other element has that value.
通过为IT
指定1
的值,当HR自动分配0
值时,不会引起任何错误,因为没有其他元素具有该值。
Of course, we can also assigned specific values to all the elements too.
当然,我们也可以为所有元素分配特定的值。
enum Department { IT = 5, Marketing = 3}enum Department { HR = 8}console.log(Department[5]) // ITconsole.log(Department[3]) // Marketingconsole.log(Department[8]) // HR
That’s it. 😎😎
而已。 😎😎
翻译自:
typescript 枚举
转载地址:http://athgb.baihongyu.com/