Convert string to enum in Typescript

Sunday Nov 17, 2019

Typescript is a typing system to turn Javascript into a typed language during development. This can be a lifesaver if we can get over the learning curve.

Uses of enums

One of the things Typescript gives us is an enum, which allows us to define a set of named constant values. We can use enums for lots of different things, and one way we can use them is for configuration via environment:


Let’s say we have a system we are working on and we have 4 different URLs depending on which environment we are in:

Here is how we setup our enum in Typescript:

export enum Environment {
  LCL = "http://localhost"
  DEV = "",
  STG = "",
  PRD = ""

Getting an enum value from a string

Now, let’s say we read a string from the environment in our application (we use the getValueFromEnvironment method that returns a string), and we need to make sure it is a valid value for the enum: value for the enum:

const environmentValue = getValueFromEnvironment("APP_ENV")
const env = Environment[environmentValue as keyof typeof Environment]

Iterating through all enum values

Finally, during testing it can be helpful to iterate through all values of an enum. We might have a method that accepts the enum as an argument and we want to test every possible enum value with that method.

We might hard-code each value, but this is painful and error-prone. We have to remember to update the test each time we add an enum value.

We can do better than that. Each enum is also a Javascript Object, so we can use Object.keys to get all of the key values as strings. Knowing our trick from above, we can easily iterate through the enum values and test all of them. This lets us add enum values as we need to without needing to update the test code to cover the new values!

Object.keys(Environment).forEach((environmentKeyValue) => {
  const env = Environment[environmentKeyValue as keyof typeof Environment]
  // env is now equivalent to Environment.PRD, Environment.STG, Environment.DEV, or Environment.LCL
  // expect(myFancyTest(env)).toEqual(...)


In this article, we saw a trick with Typescript enums that can make life much easier - how to convert a string to an enum value and how to use Object.keys to iterate over all the values.