过滤联合类型为单一类型

时间:2016-12-02 18:13:11

标签: flowtype

我定义了一个标记的联合类型,我的代码中有些地方我希望将其过滤为单一类型。

/* @flow */

type AbstractChange = {
    base: string,
};

type CreateChange = AbstractChange & { 
    kind: 'create',
    createField: string,
};

type UpdateChange = AbstractChange & { 
    kind: 'update',
    updateField: string,
};

type Change = CreateChange | UpdateChange;

function test(changes: Change[]) {
  let creates: CreateChange[] = changes.filter(c => c.kind === 'create');

  return creates;
}

不幸的是,似乎不允许,我收到错误:

19: function test(changes: Change[]) {
                           ^ intersection. This type is incompatible with 7:

type CreateChange = AbstractChange & {                        
                                     ^ object type

Here's如果有帮助,请尝试使用流量链接。

1 个答案:

答案 0 :(得分:1)

filter不够聪明,无法理解这样的改进,但它理解可能的类型

function maybeCreateChange(c: Change): ?CreateChange {
  return c.kind === 'create' ? c : null
}

function test(changes: Change[]): CreateChange[] {
  return changes.map(maybeCreateChange).filter(Boolean)
}