Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have:

    enum A {
        dog = 1,
        cat = 2,
        ant = 3
    }

Desired output: ["dog", "cat", "ant"] achieved by:

    Object.values(A)

Unfortunately, using this method results in: ["dog", "cat", "ant", 0, 1, 2]

Another issue is that the returned values (0, 1, 2) don't match the actual values (1, 2, 3). How can this be resolved?

Answer №1

Unfortunately, you cannot directly access an enum's keys in Typescript because it compiles the enum into a structure like this:

var A;
(function (A) {
    A[A["dog"] = 1] = "dog";
    A[A["cat"] = 2] = "cat";
    A[A["ant"] = 3] = "ant";
})(A || (A = {}));

You can check out this link to see how the code is compiled in the typescript playground.

However, there is a workaround to get the keys of an enum by using the following code:

Object.keys(A).filter(isNaN)

This solution works because Enums cannot contain numeric values as entries.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

The array becomes empty once values are added

While parsing an XML file, I am encountering an issue where the array remains null after adding values into it. The potential reason for this could be that I am using the same array in two different classes. In the provided code snippet, there are .h file ...

The number type in Typescript is incompatible with the string type and cannot be assigned

Currently, I am deeply involved in developing a currency formatting directive for my Angular 4 application. In the parsing process, I am stripping out all characters except digits and decimal points to convert the input into a float number. However, I ne ...

Creating an index signature in TypeScript without having to use union types for the values - a comprehensive guide

Is it possible to define an index signature with strict type constraints in TypeScript? interface Foo { [index: string]: number | string } However, I require the value type to be either number or string specifically, not a union of both types (number | ...

What is the reason for the lack of functionality of the "unique" field when creating a schema?

I've created a schema where the username field should be unique, but I'm having trouble getting it to work (The "required" constraint is functioning correctly). I've tried restarting MongoDB and dropping the database. Any idea what I might b ...

Steps for injecting strings directly into Angular2 EventBindingWould you like to learn how

Is it feasible to achieve something similar to this? <li><a href="#" target="_blank" (click)="createComponent(MYSTRINGHERE)">Departamentos</a></li> ...

Convert the binary data stored in a byte array into a readable format

I am working with a string of 1s and 0s in Java: String binaryString = "1101111110000000101010110" What is the best way to convert this string into a byte array? ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

How should JSON files stored on the server side be properly utilized in Next.js?

Currently, I have a collection of JSON files that I expose through an API endpoint on my web application for global access. This allows different parts of the application to retrieve the data by sending a fetch request to itself... However, since this inf ...

Achieving a clean/reset for a fetch using SSR in Next 13

Is there a way to update the user variable in the validateToken fetch if a user signs out later on, such as within a nested component like Navigation? What is the best approach to handle clearing or setting the user variable? Snippet from Layout.tsx: impo ...

Display on click within a nested array

Within my array of teams, I have nested arrays containing players' information. JSON file "id": 1, "Name": "TEAM A", "Active": true, "created_at": "2019-09-12T13:56:52.045Z", "updated_at": "2019-09-12T14:30:42.533Z", "Players": [ { "id": 1, ...

TypeScript: Extending a Generic Type with a Class

Although it may seem generic, I am eager to create a class that inherits all props and prototypes from a generic type in this way: class CustomExtend<T> extends T { constructor(data: T) { // finding a workaround to distinguish these two ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Ensuring compile-time checking for template enum types in C++11 with static_assert

enum PieceType { NoPieceType, Pawn, Knight, Bishop, Rook, Queen, King, AllPieces = 0, PieceType_N = 8 }; template<PieceType T> Score OutpostEvaluator() { static_assert(T == Bishop || T == Knight); // Doesn't compile..... } I am ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

Struggling to enter the command `zip` and accurately anticipating when inference fails in overloaded functions involving generics

There are times when I encounter this issue without understanding why the inference fails. Specifically, zip behaves correctly when directly used, but not when used within pipe, leaving me puzzled. declare const zip: { <A, B>(input: readonly [re ...

Trouble loading Styled Components in React Typescript with Webpack configuration

Hey there! I'm diving into the world of styled components for the first time, and I'm a bit lost on where I might have slipped up. I've got my webpack all sorted out and my .babelrc file in place. As I was going through the Styled Component ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...