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



我有一个带有值的数组:

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

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

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

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

type Currencies = $Values<currencies>

,但我有一个错误,因为$ value仅适用于对象。

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

据我所知

一种方法是将您的数组变成对象,并与$Keys一起使用CC_1

const currencies = ['USD', 'BRL', 'EUR'];
const currenciesObj = currencies.reduce((agg, next) => ({...agg, [next]: true}), {});
type Currencies = $Keys<typeof currenciesObj>;

Jamie的版本将创建另一个对象currenciesObj,该对象是为了类型的目的而创建的,并且将在缩小代码时删除的代码类型。

以下是不需要创建新对象的代码。

const xs: Array<'hi' | 'bye'> = ['hi', 'bye'];
type ArrayValues<TArr> = $Call<<T>(Array<T>) => T, TArr>;
("hi": ArrayValues<typeof xs>); // OK
("foo": ArrayValues<typeof xs>); // ERROR, "foo" not in 'hi' | 'bye'
(1: ArrayValues<typeof xs>); // ERROR, number is incompatible with string

最新更新