While coding, sometimes we need to get the length of an enum to serve the calculation process. This article will show you two ways to do this by using Object.keys()
and accessing __LENGTH
directly. Let’s find out together.
Get the length of an Enum in TypeScript.
TypeScript does not provide a method to get the length of an enum, but we can get it in the following ways.
Using Object.keys()
Object.keys() returns an array whose elements contain the string name corresponding to the key string found directly in the Object. This is similar to the iteration with the for…in
loop, except that the for…in
loop also collects the properties in the prototype chain. The order of the array returned by Object.keys()
is the same as the order returned in the for loop.
Syntax:
Object.keys(enum)
Parameters:
enum: is an enum or an object
Return Value:
Returns a string array containing the keys of an object or an enum
Example:
enum DaysOfWeek { Mondays, Tuesdays, Wednesdays, Thursdays, Fridays, Saturdays, Sundays, } // Use Object.keys() to get the elements contain the string name corresponding to the key string const DaysOfWeekArray = Object.keys(DaysOfWeek); console.log(DaysOfWeekArray);
Output:
[
'0', '1',
'2', '3',
'4', '5',
'6', 'Mondays',
'Tuesdays', 'Wednesdays',
'Thursdays', 'Fridays',
'Saturdays', 'Sundays'
]
As you can see the returned data includes the enum’s key and default value, we can get the length of this enum by dividing the length of the returned array by 2.
Example:
enum DaysOfWeek { Mondays, Tuesdays, Wednesdays, Thursdays, Fridays, Saturdays, Sundays, } const DaysOfWeekArray = Object.keys(DaysOfWeek); // Get the length of this enum by dividing the length of the returned array by 2 const LengthOfEnum = DaysOfWeekArray.length / 2; console.log("Length of the enum is " + LengthOfEnum);
Output:
Length of the enum is 7
Using __LENGTH
In addition to the above usage, we have another way which is directly accessing the __LENGTH
attribute. This is a default built-in enum property, just access it, and we can get the length of enums.
Example:
enum DaysOfWeek { Mondays, Tuesdays, Wednesdays, Thursdays, Fridays, Saturdays, Sundays, __LENGTH, } // Access the __LENGTH attribute to get the length of the enum console.log("Length of the enum is " + DaysOfWeek.__LENGTH);
Output:
Length of the enum is 7
In the above example, we declare an additional attribute to the enum named __LENGTH
, and then we use this property externally to get the length of the enum.
Summary
Through this tutorial, we have learned two ways to get the length of an Enum in TypeScript using Object.keys()
and __LENGTH
to solve work problems. Hope the article is helpful to you. Thanks for reading.

Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).