List of enums created from strings representing enum values

Is there a way to convert enum value strings to actual enums in TypeScript? While it's possible to compare strings directly (e.g. MyEnum.FirstEnum === 'My_First_Enum' would return true), I'm interested in finding a method to return enums instead of strings.

export enum MyEnum {
  FirstEnum = 'My_First_Enum',
  SecondEnum = 'My_Second_Enum',
  ThirdEnum = 'My_Third_Enum'
}

getMyEnums(): MyEnum[] {
  // These would typically be input arguments, but for this example simplicity sake, I provided them here
  const stringEnumValues = ['My_Second_Enum', 'My_Third_Enum'];

  // Convert to enums (result will currently be [undefined, undefined])
  return stringEnumValues.map(e => MyEnum[e]);
}

Answer №1

To implement the functionality, consider utilizing the Object.entries method. Proceed by applying a filter based on your specified values found in the stringEnumValues, followed by a simple map of the filtered results:

const stringEnumValues = ['My_Second_Enum', 'My_Third_Enum'];  
let result = Object.entries(MyEnum)
                      .filter(([k,v])=> stringEnumValues.includes(v))
                      .map(([ke, vl]) => MyEnum[ke]);

For a practical demonstration, you can view an example implemented on stackblitz through this link.

Answer №2

To convert your string into a key of the enum type, there are two methods you can use - one with an array of strings representing the enum keys and another with an array of strings representing the values:

Getting by keys:

getMyEnums(): MyEnum[] {

  const stringEnumValues = ['SecondEnum', 'ThirdEnum'];  
  return stringEnumValues.map( (e : keyof typeof MyEnum) => MyEnum[e])

}

Getting by values:

getMyEnums2(): MyEnum[] {

  const stringEnumValues = ['My_First_Enum', 'My_Second_Enum'];  
  return stringEnumValues.map( (e : MyEnum) => e)

}

Check out the example here: https://stackblitz.com/edit/angular-yd6yhe?file=src/app/app.component.ts

Source for more information:

Answer №3

Have you considered utilizing a frozen JSON object for this particular scenario?

const MyTypes = Object.freeze({
  'TypeOne': 'First_Type',
  'TypeTwo': 'Second_Type',
  'TypeThree': 'Third_Type',
  'First_Type': 'TypeOne',
  'Second_Type': 'TypeTwo',
  'Third_Type': 'TypeThree'
});

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

"Exploring the power of D3, TypeScript, and Angular 2

I am facing challenges incorporating D3 v4 with Angular 2 (Typescript). While exploring D3 v4, I have referred to several solutions on StackOverflow without success. I have imported most of the necessary D3 libraries and typings (utilizing TS 2.0) and adde ...

Encountering a reference type error when using drag and drop with NextJS and react-dnd

When using react-dnd version 16 with TypeScript in Next.js, the refs within the return array of the useDrag and useDrop hooks are not compatible with LegacyRef. Interestingly, other platforms like Vite.Js handle this type assignment correctly. The same co ...

Component in Angular 2 for blocking UI

How can you effectively block the user interface of an Angular 2 component? Is this the correct method to use? <component [blockUI]="true"></component> ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Removing item from Angular service

Within my Angular 2 application, I have created a service called events.service.ts: const EVENTS = { 1512205360: { event: 'foo' }, 1511208360: { event: 'bar' } } @Injectable() export class EventsService { getEvents() ...

Deriving the type of a generic parameter from another generic parameter in TypeScript

Apologies for the less-than-descriptive title of this question, but sometimes it's easier to demonstrate with code rather than words. Here's a snippet that's causing issues, and I'm wondering why it's not behaving as expected: int ...

What could be the reason behind my Ionic app receiving a 401 error from an API call while Postman is not encountering the

Following the instructions from a tutorial on Smart of the Home, I implemented the code below in a provider for my Ionic 2 App. return new Promise(resolve => { // Using Angular HTTP provider to make a request and process the response let headers = ...

Sharing code between Angular 8 and NodeJS 12: Best practices

Can code be shared between Angular 8 (TypeScript) and NodeJS 12? All the code is located on the same server but in separate directories /client and /server. A major issue we are facing is the duplication of regular expressions and constants across both A ...

Guide to dynamically including a tooltip in an input box using Angular 2

I need to implement a feature where a Tooltip message is displayed when hovering over an input box. The content of the Tooltip message will depend on the response received from a service. If the service responds with 'true', the Tooltip message s ...

404 Error: Unable to retrieve /api/posts

post.endpoint.ts class PostEndpoint implements Endpoint { public path = '/posts'; public router = Router(); private PostService = new PostService(); constructor() { this.initializeRoutes(); } private initializeRo ...

Testing the window object using Jest

I have created a function that simulates a hostname. This function is defined before the actual test, prior to the describe block. const mockHost = (hostname: string) => { global.window = Object.create(window); Object.defineProperty(window, ' ...

Creating a JSON file from a custom key-value class in Typescript: A comprehensive guide

I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class: export class TranslatedFileElement { private key: string private hasChild: boolean priva ...

Having difficulty installing node-sass in an Angular project

Having downloaded a repository from an existing Angular project, I proceeded to run sudo npm install within the project. While all packages were successfully installed, the node-sass package continued to cause issues. Upon completion of the installation ...

Is it possible to stop the Angular application from loading/bootstrapping depending on the URL, Controller, or View?

My setup consists of ASP.Net MVC/Web API working alongside an Angular 2 application, with the exception of the login process which uses a traditional MVC view and controller. While everything functions correctly when loading the login page, the console is ...

The assigned type 'string' for Apache ECharts does not match the expected type 'pictorialBar'

This demonstration is functional. Nevertheless, the options utilize any and my goal is to convert them to the EChartOption type. This is my current progress and the demonstration compiles successfully with this setup (With type: 'bar' commented ...

The element '<selector>' is unrecognized and cannot be found

Before I proceed with my query: I have gone through similar questions with the same title and followed the given advice, but none of it has worked for me. Therefore, I have decided to create a new question. In my Angular project, I have one module and mul ...

Unable to open modal window in Angular 14 micro-frontend application

I've been working on a micro front end project and running into some issues with opening modal popup windows. I've tried both the Angular material and bootstrap approaches, but ran into problems with both. With Angular material, the popup window ...

Generate a fresh class instance in Typescript by using an existing class instance as the base

If I have these two classes: class MyTypeOne { constructor( public one = '', public two = '') {} } class MyTypeTwo extends MyTypeOne { constructor( one = '', two = '', public three ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Retrieving specific properties from a JSON object and logging them

I am attempting to access JSON Object properties directly and log them using the following function : loadProcesses(filter?){ this._postService.getAllProcess(filter) .subscribe( res=> { this.processListe = res; // console.log(this.p ...