简体   繁体   中英

How can I cast a string to an enum in Typescript

Enum definition:

enum Colors {
  Red = "red",
  Blue = "blue"
}

How can I cast some arbitrary sting (eg a result from a GET request) to the enum?

const color: Colors = "blue"; // Gives an error

I understand that a union can be used here instead, but there is a library that I need to use and in this library they are using an enum. So I have to cast my string into their enum type.

In addition, why do integer enums work but string enums fail to have the same behavior?

enum Colors {
  Red = 1,
  Blue
}

const color: Colors = 1; // Works

If you are sure that the strings will always correspond to an item in the enum, it should be alright to cast it:

enum Colors {
  Red = "red",
  Blue = "blue",
}

const color: Colors = <Colors> "blue";

It won't catch the cases where the string is not valid. You would have to do the check at runtime:

let colorName: string = "blue"; // from somewhere else
let color: Colors;
if (Object.values(Colors).some((col: string) => col === colorName))
  color = <Colors> colorName;
else
  // throw Exception or set default...

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