How to Convert a TypeScript Enum to a JavaScript Array or String

Converting a TypeScript Enum to a JavaScript Array is pretty easy, and I often use it to fill a <select>
with all the values from that enum.
In this post, I love to show you how you can subtract the data from the enum and remodel it into a JavaScript Array of Strings so you can use it for whatever you like. Next, we create a generic utility function for it so that you can reuse it across your application.
What Are TypeScript Enums?
Yes, I know you are searching for a solution for turning your enum into a JavaScript Array. But do you know there are multiple ways to create an enum?
1. Numeric TypeScript Enum
The numeric enum is the most commonly used in TypeScript. You can create a numeric enum like this. (Since I love š we make a PizzaToppings enum.)
enum PizzaToppings {
TOMATO,
BBQ,
NONE,
CREAM
}
The first key in the enum gets the value 0, the second value 1, and so on. You donāt have to do anything about that. But if you want to change it, you can.
enum PizzaToppings {
TOMATO = 1,
BBQ = 2,
NONE = 3,
CREAM = 4
}
Via this, we can define the values of each key in an enum.
2. String TypeScript Enum
As it said, a string enum is an enum with values as a string.
enum PizzaSizes {
Small = 's',
Medium = 'm',
Large = 'l',
XL = 'xl',
XXL = 'XXL'
}
Via this enum, we can get string values from our enum. Super handy if you use them a lot in your application and the string value has to change š.
All these enum members are constant. But if you like to have them depending on another data type, you can make them computed.
enum PizzaSizes {
Small = "s",
Medium = "m",
Large = "l",
XL = "xl",
XXL = "XXL"
Custom = stringValueFromVar.length
}
I havenāt used this, but itās possible according to the TypeScript documentation.
3. Heterogeneous TypeScript Enums
A what you might ask? Thatās what I thought, haha! But it means an enum can have mixed values, strings, and numbers. (What Pizza Type do you prefer? I havenāt tried a vegan Pizza yet š )
enum PizzaTypes {
Vegan = 0,
NonVegan = 'No meat'
}
Now we have a PizzaTypes enum with both numeric and string values.
How To Get Single Value From A TypeScript Enum?
Sometimes you need a single value from your enum in your application.
Letās create a part of the customer's receipt when ordering the pizzas.
enum PizzaFlavours {
Peperoni = 'peperoni',
Texas = 'texas',
Tuna = 'tuna',
Hawai = 'hawai'
}
enum PizzaToppings {
TOMATO = 1,
BBQ = 2,
NONE = 3,
CREAM = 4
}
enum PizzaSizes {
Small = 's',
Medium = 'm',
Large = 'l',
XL = 'xl',
XXL = 'xxl'
}
const receiptTitle = `Pizza ${PizzaFlavours[Peperoni]} ${PizzaSizes[XXl]} with topping ${PizzaToppings[TOMATO]}`
// value = "Pizza peperoni XXL with topping 1"
In a real-world scenario, the types and flavors will not be defined as an enum in TypeScript but will come from the backend API. But for this example, it works great.
How To Get Values From A TypeScript Enum?
Now that we know how to get a value from our TypeScript enum, we can dive into our goal to get the multiple values into a JavaScript Array.
Itās pretty simple with the Object.keys()
Ā .
In the example, you can see that the console will output an Array. With both the keys and values of the enum, we can prevent that with theĀ .filter()
.
Now we can see that in the console, it will only show the strings of the values.
How To Create A Generic Utility Function For Re-usability
Now that we know our code works, we can create a super handy utility function that can turn all our enums (both string and numeric enums) into JavaScript Arrays.
function enumToArrayNames<Type>(data: Type): string[] {
return Object.keys(data).filter(
(topping: string) => !new RegExp(/[0-9]/g).test(topping)
);
}
And with this function, we can see that the function works with both string and numeric enums. š
Thanks
After reading this post, I hope you learned something new or are inspired to create something new! š¤
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DMās are always open š.
Suggestions
Mastering The JavaScript Includes() Method
Learn how to use the includes() method in JavaScript to search an array and return a boolean value indicating whether a specific value is present. Quick and easy guide for beginners."
How To Sum Total From Array Of Object Properties With JavaScript Reduce Method
Calculating the total price for your shopping cart was a hassle in the days before the JavaScript reduce method. In this post, I will show you how easy it is to use the reduce method to calculate the total price of a product array in the shopping cart. The JavaScript reduce method is powerful and can calculate a total price based on an array of object properties.
Mastering The JavaScript Find() Method
Searching specific values in arrays is easy with the JavaScript `find()` method. It doesn't matter if you want to find a string, number, boolean, or property of an object in an array. In this post, I will show you how to find values very easily. The find() Array method in JavaScript returns the first item in the array that matches your condition.