DEV Community

Discussion on: Finally, an easy way to use TypeScript enums

Collapse
 
mateiadrielrafael profile image
Matei Adriel • Edited

Ik im super late, but you can use

const foodPreferenceQuestion: Record<FoodPreference, string> = {
    [FoodPreference.vegan] : 'Do you like nuts?',
    [FoodPreference.vegetarian] : "You're really a pescatarian aren't you?",
    [FoodPreference.omnivore] : 'You are the most picky omnivore in the history of ever I bet'
};
Collapse
 
samuraiseoul profile image
Sophie The Lionhart

Oh cool! That's awesome! Thanks for commenting even if it's late! Knowledge is welcome any time! :D

Collapse
 
uselesspickles profile image
Jeff Lau

That's basically what ts-enum-util does for you behind the scenes automatically, but more. It infers the type of the value you are "visiting"/"mapping", including whether it can be possibly null or undefined, and forces you to handle null/undefined values as necessary. It also allows you to optionally provide a handler for "unexpected" values that occur at runtime, but were not part of the original compile-time enum definition. It uses unique symbols as keys for these special handlers to absolutely guarantee 0% chance of collision with legitimate enum values.

Then there's also the other side of ts-enum-util which gives you convenient access keys/values of the enum at runtime, mapping from key->value and value->key, custom type guards to verify/cast number/string values as enum values, etc.