简体   繁体   中英

Set variable of enum type by string in TypeScript

How to assign value to a variable of type enum in TypeScript?

Given

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

I need to set variable "selected" by string value and the following function does the job well:

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 write a function so that it will not be changed when enum items changes. In current function if we add 'four' to our enum we will need to add case to switch statement. And that is what I want to avoid.

You can use keyof typeof to convert string to enum. Below code will convert string to enum.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM