Home > Software engineering >  Typescript undefined error produced for defined enum
Typescript undefined error produced for defined enum

Time:04-12

In file defs.ts I define an enum and export it...

enum MyState {
    state1 = 'state1'
    state2 = 'state2'
... state5 = 'state5'
}

this gets exported to index.tsx of a Component and exported from there

export {
    MyState,
    ... 
}

It then gets imported into a file in another Component

import { MyState } from "../Component1"

const filterMap: { [key: string]: { title: string; filter: object } } = {
  s1: { title: 's1', filter: { state: MyState.state1 } },
  s2: { title: 's2', filter: { state: MyState.state2 } },
  s2: { title: 's3', filter: { state_ne: [MyState.state3 ] } },
}

However on being run, an error gets generated

Uncaught TypeError: Cannot read properties of undefined (reading 'MyState')

WTF is going on?

CodePudding user response:

I think you should do

export default {
MyState,
... 
}

Because when you import you are trying to deconstruct the default module export which you have not defined

CodePudding user response:

This works for me

defs.ts

export enum MyState {
    state1 = 'state1',
    state2 = 'state2',
    state5 = 'state5',
}

Component2.tsx

import { MyState } from './defs'
const filterMap: { [key: string]: { title: string; filter: object } } = {
  s1: { title: 's1', filter: { state: MyState.state1 } },
  s2: { title: 's2', filter: { state: MyState.state2 } },
  s2: { title: 's3', filter: { state_ne: [MyState.state5 ] } },
}

If you need to export it from an intermediary you would do something like this.

Component1.tsx

export * from './defs'

I

  • Related