Search
Close this search box.

TypeScript Enums to String

I just found an easy way to convert an enum value to its corresponding string value. Say you have the following enum.

enum Numbers { zero, one, two, three, four }

If you do Numbers.one you of course get the number 1. But let’s say you have the enum value and you want to print it out. It’s easy to get the string value by using an array indexer on the enum type.

var myNumber = Numbers.two;

var twoAsString = Numbers[myNumber]; // twoAsString == “two”

It seems a little strange but it works. If you look at the JavaScript you’ll see how it’s doing this. Click here to check it out on the TypeScript playground.

This article is part of the GWB Archives. Original Author: Phubar Baz

Related Posts