【问题标题】:Flow javascript typecheck a recursive definition with union of arrays of a single element typeFlow javascript类型检查具有单个元素类型的数组并集的递归定义
【发布时间】:2017-03-13 15:47:48
【问题描述】:

我有一个如下定义的树结构。 options 属性是 ParentActions 数组或 Options 数组。但我不确定如何让流类型检查器正确检查。

// @flow
type Option = {
  label: string,
  action: string,
  type: 'leaf'
}

type ParentActions = {
  prompt: string,
  depth: number,
  label: string,
  options: Array<ParentActions> | Array<Option>,
  type: 'parent'
}

type RootActions = {
  prompt: string,
  options: Array<ParentActions> | Array<Option>,
  type: 'root'
}

const thisDoesNotTypeCheckCorrectly : RootActions = {
  options: [
    {
      label: 'string',
      action: 'string',
      type: 'leaf'
    },
    {
      label: 'string',
      action: 'string',
      type: 'leaf'
    }
  ],
  type: 'root'
};
/* Could not decide which case to select
union type: test.js: 15
Case 1 may work:
array type: test.js: 15
But if it doesn't, case 2 looks promising too:
array type: test.js: 15
Please provide additional annotation(s) to determine whether case 1 works (or consider merging it with case 2):
inferred union of array element types (alternatively, provide an annotation to summarize the array element type) */

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    试试这个:

    type RootActions = {
      prompt: string,
      type: 'root',
    } & ({ options: Array<ParentAction> } | { options: Array<Option> })
    

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 2011-01-20
      • 2018-04-13
      • 2018-05-20
      • 1970-01-01
      • 2015-10-07
      • 2017-10-08
      • 1970-01-01
      相关资源
      最近更新 更多