Posso obter a chave enum de um valor atribuído ao usar strings enum? [duplicado]

Dec 08 2020

Posso obter a chave enum de um valor atribuído ao usar strings de enum - preciso saber qual chave é usada, não o valor da string.

Exemplo:

enum Widgets {
   Foo: 'this is foo',
   Bar: 'this is bar'
}

const current = Widgets.foo;
console.info(current); // 'this is foo';

// later on, I need to get the key of the enum used in current i.e. the value 'Foo', not the string value 'this is foo'

Codesandbox Demo

Respostas

1 HienNguyen Dec 08 2020 at 07:48

Você pode obter a chave enum usando

let key = Object.keys(Widgets)[Object.values(Widgets).indexOf(current)]

Demo https://stackblitz.com/edit/typescript-av8rkx