Search code examples
typescriptenumsundefined

Typescript runtime error: cannot read property of undefined (enum)


I have the following interface and enum in a file RESTConfig.ts:

export const enum RESTMethod {
   POST = "POST",
   GET = "GET"
}

export interface RESTConfig {
   url: string;
   method: RESTMethod;
   data: any;
}

I want to import and use the enum in another class as such:

import { RESTConfig, RESTMethod } from './RESTConfig';

class Pipelines {
   ...
   private someMethod() {
      let rest: RESTConfig = {
         url: "",
         method: RESTMethod.POST,
         data: {}
      }
      ...

   }
   ...
}

Linting and transpiling works fine, but at runtime I get the following error:

TypeError: Cannot read property 'POST' of undefined

on the line "method: RESTMethod.POST".

Can someone tell me what I'm doing wrong?


Solution

  • In Typescript there are 2 kinds of enums:

    • Classic enum:

    During TS to JS transpilation they are converted to real objects, so they exist at runtime.

    enum Response {
        No = 0,
        Yes = 1,
    }
    
    const yes = Response.Yes; // Works at runtime
    
    const nameOfYes = Response[yes]; // Also works at runtime because a reverse mapping is also generated during transpilation
    
    • const enum (the one you are using):

    Const enums are removed during transpilation in JS so you can not use them at runtime. As per TS doc const enums exists to avoid paying the cost of extra generated code and additional indirection when accessing enum values.

    const enum Response {
        No = 0,
        Yes = 1,
    }
    
    const yes = Response.Yes; // At runtime: ReferenceError: Response is not defined
    
    const nameOfYes = Response[yes]; // During transpilation: TS2476: A const enum member can only be accessed using a string literal.
    

    So just change your const enum to enum and your runtime error will be gone.