To transform an enum into an array of its values in TypeScript, you can use the Object.keys()
and Object.values()
methods. Here is a code snippet that demonstrates this approach:
index.ts132 chars8 lines
In this code, the Color
enum is defined with three values, Red
, Green
, and Blue
. The Object.values()
method is used on the Color
object to get an array of its values, which is then assigned to the values
variable. This array contains the string values "red"
, "green"
, and "blue"
, which correspond to the enum values.
Note that this approach only works for string-based enums in TypeScript. Numeric enums cannot be transformed into arrays in this way, as their values are not stored as properties of the enum object.
gistlibby LogSnag