使用数组值作为类型的流程

问题描述 投票:0回答:1

我有一个包含值的数组:

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

我想避免这样做以避免代码重复:

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

是否可以将这些值用作类型?我试着这样做:

type Currencies = $Values<currencies>

但我得到一个错误,因为$ Values仅用于对象。

不重复代码的最佳方法是什么,因为我已经在数组中有这些值。

javascript flowtype
1个回答
1
投票

据我所知,目前没有办法使用数组流程。

一种方法是将数组转换为对象,并使用$Keystypeof

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

type Currencies = $Keys<typeof currenciesObj>;
© www.soinside.com 2019 - 2024. All rights reserved.