0

here's my enum definition

export enum CallerComponent {
  HOMEPAGE= 'homepage',
  DEFAULT = 'default'
}

 callerString = 'homepage';
 const caller: CallerComponent  = CallerComponent[callerString] //I'm getting undefined...

All the page I've found say this is the way to go. Am I missing something?

Thanks for helping.

Richard77
  • 20,343
  • 46
  • 150
  • 252

2 Answers2

1

You could try something similar to this:

const callerString: string = "homepage";
Object.keys(CallerComponent).forEach((key) => {
    const component: CallerComponent = CallerComponent[key as keyof typeof CallerComponent]
    console.log(component);
});

EDIT: A google search resulted in the same question being answered( with a similar solution too)

Sagar Chilukuri
  • 1,430
  • 2
  • 17
  • 29
0

CallerComponent compiles to the dictionary like {HOMEPAGE: "homepage", DEFAULT: "default"}. What is why CallerComponent["homepage"] is undefined.

And "homepage" === CallerComponent.HOMEPAGE.

So, I 'm confused. What do you want to achieve?

UPD: Ah, I get it. I guess you tried to get a key name by the value? It works this way with regular enums, not string ones.

    export enum CallerComponent {
       HOMEPAGE,
       DEFAULT
    }


    const keyName = CallerComponent[CallerComponent.HOMEPAGE]; // HOMEPAGE

More information is here: https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings

Keep in mind that string enum members do not get a reverse mapping generated at all.

So if you really would like to reverse it by some reasons, you could play around the underlying dictionary, as you usually do in plain javascript

Yozi
  • 11,435
  • 1
  • 22
  • 25