流:将多个字符串的并集类型转换为新类型

时间:2018-06-26 21:48:38

标签: javascript reactjs types flowtype

说我有这种类型:

export type VerificationStatus = | 'TRIAL_DEPOSIT_PENDING' | 'TRIAL_DEPOSIT_REQUIRED' | 'TRIAL_DEPOSIT_EXPIRED' | 'TRIAL_DEPOSIT_VERIFICATION_FAILED' | 'TRIAL_DEPOSIT_REINITIATE' | 'VERIFIED';

我有一个哈希映射,看起来可能像这样:

verificationStatus: { trial_deposit_expired: 'Sorry, trial deposits have expired.' },

etc,其中每个键值对的名称应为上面的并集之一,并转换为小写。如何将其设置为VerificationMapKey类型,以便我可以做:const verificationStatus: {[name: VerificationMapKey]: string}

换句话说,VerificationMapKey是一个函数的返回类型,该函数对VerificationStatus的所有可能值进行迭代并将其变为小写。

1 个答案:

答案 0 :(得分:-1)

简单为:

const VerificationStatuses = ['TRIAL_DEPOSIT_PENDING',
  'TRIAL_DEPOSIT_REQUIRED',
  'TRIAL_DEPOSIT_EXPIRED',
  'TRIAL_DEPOSIT_VERIFICATION_FAILED',
  'TRIAL_DEPOSIT_REINITIATE',
  'VERIFIED'];

const VerificationStausMessagesKey = VerificationStatuses.forEach(status => status.toLowerCase());

export type VerificationStatus = $Keys<typeof VerificationStatuses>;
export type VerificationStausMessageKey = $Keys<typeof VerificationStausMessagesKey>;