1

Given an enum in typescript

enum CoffeeSizes {
  Large = 'L',
  Medium = 'M',
  ExtraLarge = 'XL',
}

CoffeeSizes.Large === 'L' // true

How do I do the reverse lookup, where I can say

CoffeeSizes.L === 'Large'

How can I create a type with the inverse enum?

user2167582
  • 5,986
  • 13
  • 64
  • 121
  • Do you want to infer the type from the existing enum, or re-define the enum? – skovy Sep 17 '19 at 03:15
  • 1
    Possible duplicate of [TypeScript: Infer enum value type from enum type](https://stackoverflow.com/questions/50227229/typescript-infer-enum-value-type-from-enum-type) – gotnull Sep 17 '19 at 03:33
  • @fuzz That link only grab values, I need an inverse enum with type. – user2167582 Sep 17 '19 at 03:45
  • Have a look [here](https://stackoverflow.com/a/48945109/5669456) for a possible reverse mapping implementation. Reverse lookups are not possible for string enums. – ford04 Sep 17 '19 at 09:42

1 Answers1

0

Reverse mappings are only possible for numeric non const enums.
As in the example below

enum CoffeeSizes {
  Large,
  Medium,
  ExtraLarge
}

const nameOffLargeCoffeeSize = CoffeeSizes[CoffeeSizes.Large];
CoffeeSizes[nameOffLargeCoffeeSize] === CoffeeSizes.Large;

You can get more details in TypeScript docs

Artem Bozhko
  • 1,744
  • 11
  • 12