DEV Community

Cover image for Should I stay or should I go? Enums in TypeScript - error case study
Konrad Winnicki
Konrad Winnicki

Posted on

Should I stay or should I go? Enums in TypeScript - error case study

The usage of enums in TypeScript is an ongoing debate. Voices for employing them as an integral part of the language can be found [Ref.], as well as those arguing against [Ref.].
Here [Ref.] you can find a very good set of bullet points which really convinces me why it is better to avoid enums in TypeScript.

Furthermore, depending on whether you are using enums or enum-like objects, you may encounter different errors if something fails. These for enums may not be straightforward to grasp at first glance. I experienced this once when, during refactoring, accidentally part of code was moved to the top of the module, resulting in the enum being referenced before it was defined. Below you can find a simplified example ( Object.values() method used to retrieve an enum properties is wrapped by the function):

function getNodeEnvValues(){
    return Object.values(NODE_ENV)
}

getNodeEnvValues()

enum NODE_ENV{
    DEV = "development",
    PROD = "production"
}
Enter fullscreen mode Exit fullscreen mode

If you try to execute this code you will get a generic TypeError Cannot convert undefined or null to object.
Type error

At first, when I saw the error I was thinking why the object which I have passed to the method is undefined. Looking at the enum definition I was trying to figure out what is really going on there.
Then I realised that the error was telling the truth since the defined enum NODE_ENV has not been reachable for the method (it was undefined at that point). However, this error may be a little confusing especially when the code is more complex. We get this error because Typescript enums are transpiled to a self-invoking function which creates key-value pairs object and assignates it to a var.

Enum after transpulation

On the other hand using enum-like object in the same situation, we will get a ReferenceError which helps to more straightforwardly identify the nature of the error.

function getNodeEnvValues(){
    return Object.values(NODE_ENV)
}

getNodeEnvValues()

const NODE_ENV = {
    DEV = "development",
    PROD = "production"
} as const
Enter fullscreen mode Exit fullscreen mode

After executing the above code we will get: Cannot access ‘NODE_ENV’ before initialization. The reference error gives you precise information indicating that the variable hasn't been declared or is out of scope.

Refference errro

How about you? Are you using enums in TypeScript, or are you trying to avoid them?

Top comments (0)