列挙型文字列を使用するときに、割り当てられた値から列挙型キーを取得できますか?[複製]

Dec 08 2020

列挙型文字列を使用するときに、割り当てられた値から列挙型キーを取得できますか?文字列値ではなく、使用されているキーを取得する必要があります。

例:

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デモ

回答

1 HienNguyen Dec 08 2020 at 07:48

を使用して列挙型キーを取得できます

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

デモ https://stackblitz.com/edit/typescript-av8rkx