Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of strings into enum

Say, I have an array const colors = ['R', 'G', 'B'] (or object const colors = {R: 'R', G: 'G', B: 'B'} which will also do). Considering typescript enums transpiled into objects, if I'm not missing anything. Is there a way to parse above array (or object) into enum dynamically?

E.g. something like (non-working pseudo-code sample for the sake of example):

type Color = colors.reduce((palette, color) => palette | color)

or

enum Color = colors.reduce((palette, color) => (palette[color] = color, palette), enum)

The whole idea behind is to turn long list of string values into enum, without hardcoding miles long type definition, like:

type Color = 'R' | 'G' | 'B' .. /* followed by gazillion more color values */
like image 851
Curr195 Avatar asked Sep 17 '26 10:09

Curr195


1 Answers

I think you need something like this:


const Colors = ['Red', 'Blue', 'Green'] as const;

type colors = typeof Colors[number] // 'Red' | 'Blue' | 'Green'

Hopefully, this will work for you :)

like image 63
Saif Ali Khan Avatar answered Sep 18 '26 23:09

Saif Ali Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!