将Javascript类型定义为另一个Object属性值的文字数组

时间:2018-06-02 17:27:51

标签: arrays flowtype

const familyTypes = [
  { id: 'COUPLE', name: 'Couple' },
  { id: 'SINGLE_LADY', name: 'Single lady' },
  { id: 'SINGLE_GENTLEMAN', name: 'Single gentleman' }
];

type State = {
  familyType?: (what can I put here?)
};

是否有一个声明会将familyType上面的文字值'COUPLE' | 'SINGLE_LADY' | 'SINGLE_GENTLEMAN'的数组设置为编程?

注意:这是在React中使用Flow;这个想法是这样的语句稍后会抛出一个静态类型错误:

var state: { familyType: 'SOMETHING_ELSE' }

2 个答案:

答案 0 :(得分:1)

您可以使用map从familytype

返回一组id



const familyTypes = [
  { id: 'COUPLE', name: 'Couple' },
  { id: 'SINGLE_LADY', name: 'Single lady' },
  { id: 'SINGLE_GENTLEMAN', name: 'Single gentleman' }
];

var State = {
  familyType:  familyTypes.map(type => type.id)
};
console.log(State)




答案 1 :(得分:0)

您需要使用$ElementType$ReadOnly的组合来完成工作。元素类型在这里很有趣:

  

$ElementType<T, K>是表示数组,元组或对象类型T中与给定键类型K匹配的每个元素的类型的类型。   ...   只要该类型存在于$ElementType<T, K>的密钥上,就可以使用KTtype familyTypes = [ { id: 'COUPLE', name: 'Couple' }, { id: 'SINGLE_LADY', name: 'Single lady' }, { id: 'SINGLE_GENTLEMAN', name: 'Single gentleman' } ]; // We want the type of elements indexed by a number type familyObjs = $ElementType<familyTypes, number> // We're only going to read from this type (this // prevents problems with variance caused if we // were to write to the value) type familyObjsReadOnly = $ReadOnly<familyObjs> // The type of the thing stored at the 'id' property type idType = $ElementType<familyObjsReadOnly, 'id'> type State = { familyType: idType }; const state1: State = { familyType: 'COUPLE' } const state2: State = { familyType: 'SINGLE_LADY' } const state3: State = { familyType: 'UH-OH' } // Error

这是在行动:

Try

familyObjs

如果您想了解我们需要使用familyObjsReadOnly的原因,请继续$ElementType代替最后$ReadOnly中的R.drawable