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']

  • 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`](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess) is disabled). Example: https://tsplay.dev/WJyQVm – jsejcksn Aug 03 '22 at 13:51
  • Does this answer your question? [How to get names of enum entries?](https://stackoverflow.com/questions/18111657/how-to-get-names-of-enum-entries) – Behemoth Aug 03 '22 at 14:04
  • [^](https://stackoverflow.com/questions/73222621/how-to-get-enum-key-with-enum-value-in-typescript#comment129317972_73222621) @Behemoth That one is for numeric enums. String enums don’t have [reverse mappings](https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings). – jsejcksn Aug 03 '22 at 14:26

2 Answers2

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

mickl
  • 48,568
  • 9
  • 60
  • 89
1

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")]);

Stanley
  • 2,434
  • 18
  • 28