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?

4
  • Do you want to infer the type from the existing enum, or re-define the enum? Commented Sep 17, 2019 at 3:15
  • 1
    Possible duplicate of TypeScript: Infer enum value type from enum type Commented Sep 17, 2019 at 3:33
  • @fuzz That link only grab values, I need an inverse enum with type. Commented Sep 17, 2019 at 3:45
  • Have a look here for a possible reverse mapping implementation. Reverse lookups are not possible for string enums. Commented Sep 17, 2019 at 9:42

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.