0

In the project i am working on we have this widely used enum:

export enum A{
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

Example: I want to get Organization with A['3']

3
  • 1
    You didn't mention this as a requirement, but I thought it might be useful to note that it's not possible for the compiler to infer the string literal value of the key during this kind of lookup, so its type will simply be string | undefined without an assertion (or just string if noUncheckedIndexedAccess is disabled). Example: tsplay.dev/WJyQVm Commented Aug 3, 2022 at 13:51
  • Does this answer your question? How to get names of enum entries? Commented Aug 3, 2022 at 14:04
  • ^ @Behemoth That one is for numeric enums. String enums don’t have reverse mappings. Commented Aug 3, 2022 at 14:26

2 Answers 2

2

Object keys

enum A {
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

console.log(Object.keys(A)[Object.values(A).indexOf("1")]);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.entries to do that:

enum A{
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

const param = '3';
const value = Object.entries(A).find(([_, v]) => v === param)![0];

TS Playground

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.