Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow using array values as type

I have an array with the values:

const currencies = ['USD', 'BRL', 'EUR']
// The true array has more then 15 currencies values

I want to avoid doing this to avoid code duplication:

type Currencies = 'USD' | 'BRL' | 'EUR'

Is it possible to use those values as types? I tried to do that:

type Currencies = $Values<currencies>

But I got an error because $Values are only for objects.

What is the best way of not duplicating the code since I already have those values in an array.

like image 289
Bruno Quaresma Avatar asked Mar 08 '26 17:03

Bruno Quaresma


1 Answers

As far as I can tell there isn't a way to do this currently with flow using an array.

One approach is to turn your array into an object and use $Keys with typeof

const currencies = ['USD', 'BRL', 'EUR'];
const currenciesObj = currencies.reduce((agg, next) => ({...agg, [next]: true}), {});

type Currencies = $Keys<typeof currenciesObj>;
like image 63
Jamie Dixon Avatar answered Mar 11 '26 06:03

Jamie Dixon



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!