Last updated: Feb 26, 2024
Reading timeยท3 min
To convert a numeric enum to a string, use bracket notation to access a
specific value on the enum to get its name, e.g.
NumericEnum[NumericEnum.Yes]
.
Similarly, you can convert a string enum to a string by using dot notation to access a specific property.
// โ NUMERIC Enums enum NumericEnum { Yes, No, Maybe, } // ๐๏ธ to string const str = NumericEnum[NumericEnum.Yes]; console.log(str); // ๐๏ธ "Yes" // ๐๏ธ to number const num = NumericEnum.Yes; console.log(num); // ๐๏ธ 0
If you have a String Enum, use the following code sample instead.
// โ STRING Enums enum StringEnum { Yes = 'Y', No = 'N', Maybe = 'M', } // ๐๏ธ to string const str = StringEnum.Yes; console.log(str); // ๐๏ธ "Y"
The first enum in the example is a
numeric enum,
where the Yes
property points to a value of 0
, No
points to a value of 1
and Maybe
to a value of 2
.
With numeric enums, we can use a reverse mapping to access the name of a specific value.
enum NumericEnum { Yes, No, Maybe, } // ๐๏ธ Both lines do the same console.log(NumericEnum[0]); // ๐๏ธ "Yes" console.log(NumericEnum[NumericEnum.Yes]); // ๐๏ธ "Yes"
Passing a specific value of the enum between the brackets enables us to convert it to a string by getting the corresponding name.
I've also written an article on how to convert a string to an enum in TS.
If you need to convert a numeric enum to a number, access a specific property using dot notation.
// โ NUMERIC Enums enum NumericEnum { Yes, No, Maybe, } // ๐๏ธ to number const num = NumericEnum.Yes; console.log(num); // ๐๏ธ 0 console.log(typeof num); // ๐๏ธ "number"
Similarly, you can convert a string enum to a string by accessing one of the names in the enum using dot notation.
// โ STRING Enums enum StringEnum { Yes = 'Y', No = 'N', Maybe = 'M', } // ๐๏ธ to string const str = StringEnum.Yes; console.log(str); // ๐๏ธ "Y"
Note that reverse mappings don't work for string enums. String enum members do not get a reverse mapping generated at all.
Enums are real objects in TypeScript, so you can use the Object.keys()
and
Object.values()
methods to get an array of the enum's names or values.
// โ STRING Enums enum StringEnum { Yes = 'Y', No = 'N', Maybe = 'M', } const names = Object.keys(StringEnum); console.log(names); // ๐๏ธ ['Yes', 'No', 'Maybe'] const values = Object.values(StringEnum); console.log(values); // ๐๏ธ ['Y', 'N', 'M']
This works similarly with numeric enums.
// โ NUMERIC Enums enum NumericEnum { Yes, No, Maybe, } const names = Object.keys(NumericEnum).filter((v) => isNaN(Number(v))); console.log(names); // ๐๏ธ ['Yes', 'No', 'Maybe'] const values = Object.values(NumericEnum).filter((v) => !isNaN(Number(v))); console.log(values); // ๐๏ธ [0, 1, 2]
However, the Object.keys()
method returns an array containing the enum's names
and values, so you have to use the filter
method to filter out the unnecessary
values.
You can learn more about the related topics by checking out the following tutorials: