How to find the length of enum data in typescript

Enum is built into the data type used to store multiple contents in a single namespace.

Sometimes, a developer needs to find several elements of an enum in javascript/typescript.

You can check my other posts on typescript Enum object.

There is no inbuilt method to find out the length(size) of properties of an enum.

Let’s declare enum constants in JavaScript, The same code works in Typescript.

export enum Color {
    RED = "#FF0000",
    GREEN="#008000",
    YELLOW = "#FFFF00",
    BLUE="#0000FF",
    MAROON="#800000"
}
console.log(Color);

Enum-type object length is several elements.

Multiple ways we can find the length of Enum properties constants.

typescript Enum length examples

There are multiple ways to check the size of an enum type.

First, Using manual counting

  • For loop within the operator used to iterate the elements of an array and increment the counter, finally, prints counter values.

Second, using object methods keys(), values(), and entries() methods to get the array list of keys, values, and key-value multiple constants.

These methods return the array of enum constants. using the length method on the array prints the size.

// manual counting using counter
var size = 0;
for (let element in Color) {
  if (isNaN(Number(element))) {
    size++;
  }
}
console.log("size= " + size); // 5
// Using object method counter
const values = Object.values(Color);
const keys = Object.keys(Color);
const entries = Object.entries(Color);

console.log(values.length); //5
console.log(keys.length); // 5
console.log(entries.length); //5

Summary

To summarize, Typescript has no built-in method for finding the length of an enum. You can find the length of enum constants with the above methods in Typescript with an example.