如何组合交集和联合类型

时间:2017-07-13 23:38:41

标签: ecmascript-6 flowtype

需要通过属性Base'扩展'基本类型c。 以下code

/* @flow */

export type A = 'a1' | 'a2';
export type B = | 'b1' | 'b2' | 'b3' | 'b4';


type Base = {
  type: A,
  a: number,
} | {
  type: B,
  b: number,
};

type Derived = {
  c: boolean;
} & Base; // #17

const f = (x: Derived) => { // #19
  if(x.type === 'a1') {
    x.a = 3; // #21
  }
  if(x.type === 'b1') {
    x.b = 3; // #24
  }
}

结果

19: const f = (x: Derived) => {
                  ^ intersection type. This type is incompatible with
17: } & Base;
        ^ union: object type(s)
21:     x.a = 3;
     ^ assignment of property `a`. Property cannot be assigned on any member of intersection type
21:     x.a = 3;
     ^ intersection
24:     x.b = 3;
     ^ assignment of property `b`. Property cannot be assigned on any member of intersection type
24:     x.b = 3;
     ^ intersection

除了向工会的两个成员添加相同的道具c之外,还有其他解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以撤消此操作并将DerivedBaseABaseB结合起来,并将公共属性与两个基数(working example)的交集添加:< / p>

/* @flow */

export type A = 'a1' | 'a2';
export type B = | 'b1' | 'b2' | 'b3' | 'b4';

type Base = {
  c: boolean;
};

type BaseA = Base & {
  a: number,
  type: A,
};

type BaseB = Base & {
  b: number,
  type: B,
};

type Derived = BaseA | BaseB;

const f = (x: Derived) => {
  x.c = true;
  if(x.type === 'a1') {
    x.a = 3;
  }
  if(x.type === 'b1') {
    x.b = 3;
  }
}