열거 형 문자열을 사용할 때 할당 된 값에서 열거 형 키를 가져올 수 있습니까? [복제]

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

사용하여 enum 키를 얻을 수 있습니다.

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

데모 https://stackblitz.com/edit/typescript-av8rkx