Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below:

export enum SomeErrorCodes {
    none = 0,
    notFound = 1,
    duplicated = 2
}

Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How can I convert these into SomeErrorCodes.notFound in TypeScript?

Appreciate any help!

Answer №1

Your enumeration will be converted into

Object
0: "none"
1: "notFound"
2: "duplicated"
duplicated: 2
none: 0
notFound: 1

This allows you to easily retrieve a value by its corresponding key,

function getErrorCode(code: number): string {
  return SomeErrorCodes[code] || 'Code does not exist';
}

Answer №2

To access the key name and retrieve the corresponding enum, you can utilize Object.keys method followed by mapping to the appropriate enum. Check out the working solution on https://www.typescriptlang.org/play/index.html for a complete understanding:

enum Fruits {
    Apple = 1,
    Orange
}

enum Vegetables {
    Carrot = 75,
    Lettuce = 88,
    Asparagus = 96
}

class CustomParser {
    public GetValues(dataObject: any): string[] {
        const customStrings: string[] = [];
        const firstKey = Object.keys(dataObject)[0];

        let fetchStringMethod: (value: number) => string;

        switch (firstKey) {
            case "Fruits":
                fetchStringMethod = (fruit: number) => {
                    return Fruits[fruit];
                }
                break;
            case "Vegetables":
                fetchStringMethod = (veg: number) => {
                    return Vegetables[veg];
                }
                break;
            default:
                throw "Unknown enum...";
        }

        const integerValues = (<string>dataObject[firstKey]).split(",")
            .map(x => Number.parseInt(x.trim()));


        for (const intValue of integerValues) {
            customStrings.push(fetchStringMethod(intValue));
        }

        return customStrings;
    }
}

const customParser = new CustomParser();
let fruitsElement = document.createElement('h2');
fruitsElement.textContent = customParser.GetValues({ "Fruits": "1,2" }).join(", ");
document.body.appendChild(fruitsElement);
let veggiesElement = document.createElement('h2');
veggiesElement.textContent = customParser.GetValues({ "Vegetables": "88" }).join(", ");
document.body.appendChild(veggiesElement);

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

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Creating a Typescript interface with at least one specified type

I've recently delved into using typescript. Currently, I'm faced with a scenario where I need to import available types from backend endpoints. In one specific instance, an endpoint can support two types as parameters. Example: interface B ext ...

Is there a way in Typescript to convert an array of variables from class A to class B, where class B is an extension of class A?

Hopefully this question is unique, as I couldn't find anything similar. I have created a definition for Array<Tag>, but now I want to change it to Array<TogglableTag>. The only difference between the two classes is an additional property. ...

Angular select element is not functioning properly with the `addEventListener` method

My current project involves creating a table using the primeng library. The table consists of three rows and three columns, and all the data is static. Even though I am utilizing an external library, I find myself traversing the DOM directly. <p-table ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Error: Attempting to initiate a backward navigation action while already in the process. Utilizing Natiescript

I encountered an issue with the routing code in my Nativescript app. Here is the code snippet: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ {path: 'fp&apos ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

Testing Jasmine with objects that contain optional properties

In the IData interface, there are optional properties available. interface IData { prop1: string, prop2?: string } setObj(){ prop1 = 'abc'; prop2 = 'xyz'; let obj1 : IData = { prop1: this.prop1, ...

What is the best way to transfer user data from the backend to the frontend?

I successfully created a replica of YelpCamp using Node and EJS, but now I am attempting to convert it into a Node-React project. Everything was going smoothly until I encountered an issue while trying to list a specific user in the SHOW route. In order to ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

The functionality of verifying the type of an item in a list using Typescript is not functioning

In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff. type NameValue = { name: string; value: string }; type MixedStuff = NameValue | string; function stripTwoChars(stuffs: MixedStuff[]): string { let st ...

The Intl.DateTime formatter consistently generates incorrect times even after refreshing the component in a React application

Our component is responsible for receiving information from the backend and rendering it. The properties of the component are defined as: interface CitizenshipProps { citizenship?: Citizenship; name?: string; lastName?: string; onUpdateClic ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...

I'm having trouble establishing a connection with the Appwrite platform

Encountered an issue while trying to connect to appwrite. The specific error message is: Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL at Account.<anonymous> (appwrite.js?v=d683b3eb:932:19) at Generator.nex ...

Unlocking the Potential of Vue Class Components: Exploring Advanced Customization Options

Currently, I am working on a project using Vue 2 with Typescript. However, I am facing an issue where I cannot add options to the component. <script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import HelloW ...

Ways to identify browser version in Angular 4 to discourage IE usage

Is there a method in Angular 4 (TypeScript) for detecting the browser type? I am currently working with Angular 4 and would like to explore options for identifying the browser type when my application is loaded. I specifically want to prevent my applicati ...

You cannot assign multiple properties with the same name to an object literal

I am facing an issue with two validator functions in my TypeScript file. The first validator checks if a user enters a new password same as the old one, displaying an error if so. The second validator ensures that "new password" and "confirm password" must ...

Interpolation is not available for my Angular application

I am having trouble with using interpolation on my input in this code. I tried setting the value of the input to be the same as the User's username, but it doesn't seem to work. <ion-header> <ion-toolbar> <ion-buttons slot=&q ...