What is the best way to convert an enum into an array containing all the values of its items in TypeScript?

For example, consider the following TypeScript enum:

export enum UserType {
    Guest = 1,
    SNS = 2,
    Account = 3,
    Certified = 4,
}

Is there a way to dynamically create an array with specific values without hard-coding them?

        const atrributeOptions = [
            {
                type: UserType.Guest,
                isSelect: filterCondition.filter((item) => item.type === UserType.Guest)[0].isSelect,
                onClick: this.onToggleFilterItem.bind(this, UserType.Guest),
            },
            {
                type: UserType.Certified,
                isSelect: filterCondition.filter((item) => item.type === UserType.Certified)[0].isSelect,
                onClick: this.onToggleFilterItem.bind(this, UserType.Certified),
            },
            {
                type: UserType.Account,
                isSelect: filterCondition.filter((item) => item.type === UserType.Account)[0].isSelect,
                onClick: this.onToggleFilterItem.bind(this, UserType.Account),
            },
            {
                type: UserType.SNS,
                isSelect: filterCondition.filter((item) => item.type === UserType.SNS)[0].isSelect,
                onClick: this.onToggleFilterItem.bind(this, UserType.SNS),
            },
        ];

Answer №1

If your enum consists of only numeric values, you can follow these steps:

export enum UserType {
    Guest = 1,
    SNS = 2,
    Account = 3,
    Certified = 4,
}

const UserTypeEntries = Object.entries(UserType)
    .filter((e): e is [keyof typeof UserType, number] => typeof e[1] === 'number');

// extract values
const UserTypeValues = Object.values(UserType)
    .filter((e): e is UserType => typeof e === 'number');

You can then map the values to attribute options like below:

const atrributeOptions = UserTypeValues.map(userType => ({
    type: userType,
    isSelect: filterCondition.filter((item) => item.type === userType)[0].isSelect,
    onClick: this.onToggleFilterItem.bind(this, userType),
}));

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

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

What is the method to remove curly brackets from a different data category?

If I have a type like this type Z = {a: number} | {} | {b: boolean} | {c: string} | ...; Is there a way to get the same type but without {}? type Y = Exclude<Z, {}>; ⇧This will result in Y = never, because all variants can be assigned to {} and a ...

Can someone provide guidance on organizing an array of objects by a specific property value using Powershell?

Let's say I have a variable that contains a line with several arrays: @{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10} My goal is to sort this line alphabeti ...

The TypeScript Type inside the Node Module Doesn't Seem to Be Functioning

In my React project, I am using the material-ui@next library along with typescript. Below is the code snippet that I have written: <CardMedia image={item.image_url} style={{ width: 238, height: 124.5 }} /> However, when I try to compile this code, ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Exploring the functions and arrays in Excel VBA

I am currently experimenting with a new concept: In my project, I have a list of names, and I am trying to read the cell values in an array to run a check on every cell in the worksheet. If a cell matches a string inside the array, I want to perform a spe ...

When attempting to refresh the page, an error occurred stating: 'Unhandled TypeError: Cannot access properties of undefined (reading FetchApi.js:23 'data')'

Upon the initial run of the code, the mappings data appear as desired. However, upon refreshing the page, an error is displayed. Can someone please advise on how to rectify this error and what could be causing it? The provided code: import React, { useE ...

Manipulating, modifying, and verifying distinct information rather than inputting to / retrieving from the model through the use of Reactive Forms

My configuration I am retrieving a value from the database as a number. This value must always be a number, except when displaying it in an input element and validating user input. In those cases, the number needs to be a HEX value. Here is the desired p ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

Using TypeScript to import the fs module

Although it may appear as a repeated question, none of the solutions I've come across seem to resolve the issue: Within my .ts file: import * as fs from 'fs'; // error: SyntaxError: Unexpected token * // OR import fs from 'fs'; / ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

`As the input value for these methods`

I am encountering an issue when trying to pass in this.value as a method argument. The field values are all strings and the constructor arguments are also all strings, so I don't understand why it's not working. When I attempt to pass in this.cla ...

Tips for setting up nextjs with typescript to utilize sass and nextjs font styles

I am attempting to configure a Next.js TypeScript app to work with Sass and a font in Next.js. I have been following the steps outlined in this article. Without the font module, styles are working correctly. Below is my next.config.js without the font co ...

Index irregularities when traversing a 2D array

My typedef'ed struct looks like this: typedef struct { int x, y; }TPosition; I've written a function that finds and returns the position of the first non-negative element in a two-dimensional array: TPosition findStartPosition(int **ar ...

Iterating through a set of HTML elements and making updates using a forEach loop

I have encountered an issue while attempting to update a group of HTML elements within a forEach loop. Initially, everything appears to be functioning correctly up to section 3. However, upon adding a new section, the problem arises where the navigation ba ...