彻底迭代字符串联合中的所有值?

spi*_*ech 2 typescript

我有一个像这样的字符串联合:

export type Intervals = 'total' | 'weekly' | 'biweekly' | 'monthly' | 'annually';

我想通过循环联合值的数组来向用户显示这些:

const intervals = ['total', 'weekly', 'biweekly', 'monthly', 'annually'];
intervals.forEach(...);
Run Code Online (Sandbox Code Playgroud)

如何输入intervals数组以保证它具有并集的所有值Intervals

Pat*_*Pat 7

不是从类型派生数组,而是从数组派生类型。

export const INTERVALS = ['total', 'weekly', 'biweekly', 'monthly', 'annually'] as const;

const temp = [...INTERVALS];
export type Interval = typeof temp[0];
Run Code Online (Sandbox Code Playgroud)

  • 更简单:`export type Interval = typeof INTERVALS[number];` (3认同)
  • 这行中的“数字”代表什么? (3认同)