Assigning enum type variable using string in TypeScript

How can I dynamically assign a value to a TypeScript enum variable?

Given:

enum options { 'one' = 'one', 'two' = 'two', 'three' = 'three'}
let selected = options.one

I want to set the variable "selected" based on a string value, and the following function accomplishes this:

function setSelected (newOption: string): void {
  switch (newOption) {
    case 'one':
      selected = userThemePreferences.one
      break
    case 'two':
      selected = userThemePreferences.two
      break
    default:
      selected = userThemePreferences. three
      break
  }
}

Is it possible to create a function that remains unaffected by changes in the enum items? Currently, if we add 'four' to our enum, we would need to update the switch statement cases. How can we avoid this scenario?

Answer №1

To convert a string to an enum in TypeScript, you can use the keyof typeof method. The code snippet below demonstrates this conversion:

enum options { 'one' = 'one', 'two' = 'two', 'three' = 'three'}

let selected: options = options.one;
const newOption = "two";

console.log(selected); //prints "one"

selected = options[newOption as keyof typeof options];
// Handle if newOption is not a valid enum string
if(selected === undefined){
    selected = options.three;
}

console.log(selected); //prints "two"

Typescript Playground

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

Issue with binding nested ViewModels/components in Knockoutjs using TypeScript does not resolve

Struggling with implementing a viewModel within another viewModel in knockout. Any assistance would be greatly appreciated. Using typescript and aiming to have a list of address controls, each with their individual viewmodel. Initially, the project functi ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Overriding the 'first' attribute in PrimeNG's lazy table when implementing filtering

I encountered an issue while attempting to set up a primeNG table using query parameters. For example, when accessing , the data displayed should pertain to "Joe" and start at the 20th entry. To handle the large volume of data my backend can provide, lazy ...

Typescript and RxJS: Resolving Incompatibility Issues

In my development setup, I work with two repositories known as web-common and A-frontend. Typically, I use npm link web-common from within A-frontend. Both repositories share various dependencies such as React, Typescript, Google Maps, MobX, etc. Up until ...

The deployment of my Node application on Heroku is causing an error message: node-waf is not

I've been trying to deploy my Node.js application on Heroku by linking it to my Github repository and deploying the master branch. Despite experimenting with various methods, I keep encountering the same error every time. You can view the detailed b ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Access the most up-to-date information through the API URL

Objective: Whenever the 'Test' Button is clicked, new data must be fetched from the backend using the API link and displayed on the modal form. Issue: If text in the input box is changed or deleted, then the modal is closed and the 'Tes ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account. Below is the error message in the browser console: page.tsx:14 POST http://localhost:3000/api/auth/ ...

The Azure function encounters an AuthorizationFailure error while attempting to retrieve a non-public file from Azure Blob Storage

Within my Azure function, I am attempting to retrieve a file from Blob Storage labeled myappbackendfiles. The initial code (utils/Azure/blobServiceClient.ts) that initializes the BlobServiceClient: import { BlobServiceClient } from "@azure/storage-bl ...

Nexus and GraphQL: The root typing path for the "context" type is not found

I’m currently working on integrating GraphQL into Next.js API routes. For writing the GraphQL schema, I’m utilizing Nexus. Here are the two essential files: context.ts and schema.ts, that help in setting up Nexus development mode. // context.ts import ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a string. The Vetur plugin has alre ...

Error encountered in Angular/Ramda while using mapAccum with an array of objects in Typescript

I am having difficulties implementing Ramda in an Angular 6 / TypeScript environment. "ramda": "^0.25.0", "@types/ramda": "^0.25.24" This is how I have started: const addP = (p1,p2) => ({ x: p1.x+p2.x,y: p1.y+p2.y }); const accum = (a,b) => [add ...

Angular2 ngFor, encountering undefined property

Having an issue where one of my properties is showing as "undefined" even though it is defined. Can't seem to find a solution: I have a parent component with the following data: @Component({ selector: "app-my-products", templateUrl: ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

There is no overload match for the HttpClient.get call at this time

I'm trying to set up a file download feature using a blob, but I need to extract the filename from the server's "content-disposition" header. Here's the code I have: const header = {Authorization: 'Bearer ' + token}; const config ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...