如何从值数组中创建联合类型?

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

$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
2个回答
1
投票

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

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>;

0
投票

我认为不可能这样做。 transitions数组中的值是运行时值,而类型是编译时抽象。换句话说,编译器无法查看数组内部,因为它本质上不存在(或者至少不存在具有值的事物)。您可能必须单独定义转换类型并在它们之间创建联合类型。

很酷的想法。 :)

© www.soinside.com 2019 - 2024. All rights reserved.