0
(0)

In Typescript enums are primarily made for constants with number values. What I mean is, if you create an enum with a list of property names, automatically it will assign to each property a numeric value in an incremented fashion. Just like the counter in CSS or the Ordered List automatic numbering in HTML5 the enum list of constants will have a 0 based numbering with incrementation for each item.

This will result in the following outcome:

In HTML5 ordered list can start from another value then the default, by specifying it:

In Typescript with enums this is done by specifying a value for the first enum item:

The value of the first item will give the reference number for the rest. Now the second thing that comes in my mind is to have an incrementation by a different value then one.

Can we increment enums by higher numbers then 1?

Well, the simple answer is NO, it is not implemented. Also since enums are like a collection of constants, they have the superpower of immutability. It is just like creating an object with the Object.freeze() method.

But of course objects don’t have the automatic numbering function implemented. Enums on reassignment would return compile errors just like the constants. Also reversing the numbering of the enums is not implemented, so don’t try to start the value from 10 and on the last item have 0, because it just won’t happen.

Since enums are like objects, they can be accessed the same way as object properties:

const March = Months.March;
//or
const March = Months["March"]

What’s cool about enum is that you can also access the property by it’s value, this is called reverse mapping.

const March = Months[3]; // March

How cool is that? Also you iterate through the enum just like you would with an object:

for (const item in Months) {

}
// or just using static methods like
Object.keys(Months);
Object.values(Months);

Also the incrementation of the enum can be interrupted anytime with a new value, even a value resulted from a mathematical(Computed) operation from the values of the enums items.

This will result in the following:

Of course you can also put strings as values.

From March till December the values will be undefined if you try to use it.

How do you merge 2 enums?

The simple answer is you can do it wit all the methods that unite 2 objects or you can use the union type:

type joinedEnums = enum1 | enum2

You could use also the spread method:

const joinedEnums = { ...enum1, ...enum2  }

Notes: The enums name should be camelcased. Also it is not invalid but not best practice to use Heterogeneous  enums (you can mix strings and numbers as values).

Conclusion:

If you want a collection of constants that are type-safe/immutable and you don’t want to add dynamically new items to the collection then enums are a good option for that.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.