首页 > 解决方案 > 如何从值数组中创建联合类型?

问题描述

$Keys并且$Values很有用,但是如果我想创建这种联合类型,它们将无济于事:

type Screen = 'screen1' | 'screen2' | 'screen3';

const transitions = [
  {name: 'from1to2', from: 'screen1', to: 'screen2'},
  {name: 'from2to3', from: 'screen2', to: 'screen3'},
  {name: 'from3to2', from: 'screen3', to: 'screen2'},
  {name: 'from2to1', from: 'screen2', to: 'screen1'},
];

// DRY here! But how?
type Transition = 'from1to2' | 'from2to3' | 'from3to2' | 'from2to1';

感谢您的任何建议!

标签: flowtype

解决方案


到目前为止,看起来最好的解决方案是这样的解决方法:

type Screen = 'screen1' | 'screen2' | 'screen3';

const transitionsConfig = {
  from1to2: {from: 'screen1', to: 'screen2'},
  from2to3: {from: 'screen2', to: 'screen3'},
  from3to2: {from: 'screen3', to: 'screen2'},
  from2to1: {from: 'screen2', to: 'screen1'},
};

const transitions = Object.keys(transitionsConfig).map(k => ({
  name: k,
  ...transitionsConfig[k],
}));

type Transition = $Keys<typeof transitionsConfig>;

推荐阅读