{

How to find the length of enum data in typescript


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

Sometimes, As a developer need 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 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);

Length of enum properties in Javascript/typescript

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

First, 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.

var size = 0;
for (let element in Color) {
  if (isNaN(Number(element))) {
    size++;
  }
}
console.log("size= " + size); // 5

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, you learned the length of enum constants in Typescript with an example.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.