Posso ottenere la chiave enum da un valore assegnato quando utilizzo stringhe enum? [duplicare]
Dec 08 2020
Posso ottenere la chiave enum da un valore assegnato quando si usano le stringhe enum: devo ottenere quale chiave viene utilizzata, non il valore della stringa.
Esempio:
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
Risposte
1 HienNguyen Dec 08 2020 at 07:48
Puoi ottenere la chiave enum usando
let key = Object.keys(Widgets)[Object.values(Widgets).indexOf(current)]
Demo https://stackblitz.com/edit/typescript-av8rkx