Fix - (Enum) cannot read property of undefined Error in TS

avatar

Borislav Hadzhiev

Tue Feb 15 20222 min read

Fix - (Enum) cannot read property of undefined Error in TS #

The enum error - cannot read property of undefined occurs for 2 main reasons:

  1. Using const enums that get removed during compilation.
  2. Having circular imports (importing members between the same files).

To solve the enum error - "cannot read property of undefined", make sure to remove the const keyword when declaring your enums and remove any circular imports from your codebase.

index.ts
export const enum Sizes { Small = 'S', Medium = 'M', Large = 'L', }

The example above declares a const enum.

Const enums can only use constant enum expressions and are completely removed during compilation.

Using const enums can be very confusing and is often discouraged.

Regular enums in TypeScript are real objects and exists at runtime. However, const enum members are inlined at use sites and will not be available at runtime, which might cause the error.

Another common thing to lookout for is having circular imports (importing and exporting members between the same files).

Here is an example of having circular imports.

index.ts
import { EmailStatus } from './another-file'; // ✅ For String Enums export enum Sizes { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ Use EmailStatus here

And here is the other file which imports the Sizes enum.

another-file.ts
import { Sizes } from './index'; export enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } // 👇️ Use Sizes here

We are importing and exporting members between the two files, so they depend on one another.

This is very confusing for the TypeScript compiler and should be avoided.

Instead you can move the enums to a single file, export them, and make use of them in another file, without having circular imports between the two files.

index.ts
import { EmailStatus, Sizes } from './another-file'; // 👇️ Use EmailStatus and Sizes here

And here is the content of the other file.

another-file.ts
export enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } export enum Sizes { Small = 'S', Medium = 'M', Large = 'L', }

Now we don't have any circular imports between the two files and TypeScript won't get confused when running our code.

Use the search field on my Home Page to filter through my more than 1,000 articles.