Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  120] [ 7]  / answers: 1 / hits: 27803  / 4 Years ago, thu, july 9, 2020, 12:00:00

Enum definition:


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

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


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

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

More From » node.js

 Answers
8

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...

[#50820] Thursday, June 25, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalynnkathrynd

Total Points: 273
Total Questions: 101
Total Answers: 93

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;