Exploring the process of associating a string with a specific enum value in TypeScript

One scenario is if you receive a string value from the server and have an enum type with string values defined. In TypeScript, how can you convert the string value to the enum type?

export enum ToolType {
  ORA= 'orange', ST= 'stone' , DP= 'dupe'
}

const stringFromServer='orange';
// You need to transfer it to ToolType.ORA

Answer №1

To receive ORA if stringFromServer='orange' or ST if stringFromServer = 'stone'

You can achieve this by utilizing JavaScript's Filter function to check for your specific condition and return true when it matches, otherwise false. This will result in an array with the desired data.

var value = 'orange';
let enums = Object.keys(ToolType).filter(x => 
{
  if(ToolType[x] === value){    
    return true;    
  }
  return false;
});

The array enums will contain:

enums[0] = ORA

For a demonstration, you can visit the following link:

https://stackblitz.com/edit/typescript-byg8ct

Answer №2

When the server transmits an enum, it actually transmits a numerical representation of that enum rather than its actual types.

One way to handle this is by defining your enum like so:

type ToolType = 'Apple' | 'Rock' | 'Copy';

const receivedString: ToolType = 'Apple';

Your client needs to be aware of the specific numerical values assigned to each value in the enum.

You might consider adjusting your server to send the string name of the enum instead and then using the code snippet provided above.

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

Create a debounced and chunked asynchronous queue system that utilizes streams

As someone who is new to the concept of reactive programming, I find myself wondering if there exists a more elegant approach for creating a debounced chunked async queue. But what exactly is a debounced chunked async queue? While the name might need some ...

Tips for executing numerous asynchronous tasks in Ionic 3 and closing a loader once all tasks are completed

Currently, I am in the process of developing an Ionic 3 application that offers the feature to cache a list of articles content on demand. The implementation involves utilizing Storage which employs promises for its operations. The code snippet I have wri ...

I am encountering an issue where my TSX import is being declared but not read when I attempt to pass it to the Jest render method. Can anyone explain

My Jest test file includes a simple import of a TSX component in my nextjs 13 project. However, when I try to use the component as a TSX tag, an error occurs: "'Properties' refers to a value, but is being used as a type here. Did you mean ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

What is the alternative method for applying a CSS class in the click event in Angular 7 without relying on ng-Class or ng-Style?

Is there a way to dynamically add or remove CSS classes to HTML elements in Angular7 without relying on Ng-Style and Ng-Class directives? I'd like to achieve this functionality when clicking on the elements. Appreciate any insights you can provide. T ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...

Navigating a text input field in a NextJS application

Having trouble with handling input from a textarea component in a NextJS app. This is the structure of the component: <textarea placeholder={pcHld} value={fldNm} onChange={onChangeVar} className="bg-cyan-300" ...

Obtaining distinct form control values for replicated form fields with Angular

Issue with Dynamic Form Duplicates: I am currently working with a reactive form that has two fields - name and value. There is an add button that duplicates the form by copying these fields. The challenge I am facing is with updating the values of the dup ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...

The library "vue-property-decorator" (v10.X) is causing issues with resolving in Webpack despite being successfully installed

Encountered an error message Module not found: Error: Can't resolve './decorators/Emit' while attempting to import functionality from the library vue-property-decorator. The package is installed and accessible, ruling out a simple installati ...

Best Practices for Organizing Imports in Typescript to Prevent Declaration Conflicts

When working with TypeScript, errors will be properly triggered if trying to execute the following: import * as path from "path" let path = path.join("a", "b", "c") The reason for this error is that it causes a conflict with the local declaration of &ap ...

Enhancing many-to-many relationships with additional fields in Objection.js

I have a question that I haven't been able to find a clear answer to in the objection.js documentation. In my scenario, I have two Models: export class Language extends BaseId { name: string; static tableName = 'Languages'; st ...

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Is there a syntax issue in your Angular/Typescript code?

I am currently developing a login system using Angular and Firestore, and here is the code I have written: import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import * as firebase from 'firebase/ ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...