flowtype - 如何从值数组中创建联合类型?
问题描述
$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';
感谢您的任何建议!
解决方案
到目前为止,看起来最好的解决方案是这样的解决方法:
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>;
推荐阅读
- java - Infinispan:cache_size 度量使用的单位是什么?
- python - 当一个属性依赖于 2 个类时,它应该定义在哪个类上?
- html - Vue - 意外的令牌'<'
- php - 如何在 Nova laravel 上首先显示编辑/删除按钮
- c# - 如何从查询选择中填充元组
- c# - VS 2019 Unity 命名空间不起作用(c#)
- c++ - 从已排序的向量中删除重复项
- ejabberd - 如何从 ejabberd 获取用户的最后一次活动?
- python - Tensorboard 中的 HParam,运行 ID 和命名
- postgresql - postgresql plpgsql:无法遍历 varchar[] 类型的数组