Borislav Hadzhiev
Tue Feb 15 2022·2 min read
Photo by Giovanni Moschini
The enum error - cannot read property of undefined occurs for 2 main reasons:
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.
export const enum Sizes { Small = 'S', Medium = 'M', Large = 'L', }
The example above declares a const enum.
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.
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.
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.
import { EmailStatus, Sizes } from './another-file'; // 👇️ Use EmailStatus and Sizes here
And here is the content of the other file.
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.