我有一个包含值的数组:
const currencies = ['USD', 'BRL', 'EUR']
// The true array has more then 15 currencies values
我想避免这样做以避免代码重复:
type Currencies = 'USD' | 'BRL' | 'EUR'
是否可以将这些值用作类型?我试着这样做:
type Currencies = $Values<currencies>
但我得到一个错误,因为$ Values仅用于对象。
不重复代码的最佳方法是什么,因为我已经在数组中有这些值。
据我所知,目前没有办法使用数组流程。
一种方法是将数组转换为对象,并使用$Keys
和typeof
const currencies = ['USD', 'BRL', 'EUR'];
const currenciesObj = currencies.reduce((agg, next) => ({...agg, [next]: true}), {});
type Currencies = $Keys<typeof currenciesObj>;