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?
To resolve your TypeError: Cannot read properties of undefined (reading '0') , go through these steps: Ensure you are using the correct variable. Perform a simple check on your variable before using it to make sure it is not undefined. Create a default value for the variable to use if it does happen to be undefined.
The "Cannot read properties of undefined" error occurs when trying to access a property on an undefined value. You often get undefined values when: accessing a property that does not exist on an object. accessing an index that is not present in an array.
To fix Error: TypeError: Cannot read property '…' of undefined with Angular, we should make sure the variable we're rendering is defined. to use the safe navigation operator if foo and bar are objects. We use arr && arr. length > 0 to make sure arr is defined and it has length bigger than 0.
I just found out the hard way that this can also happen if you have circular imports.
In Typescript there are 2 kinds of enums:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With