【问题标题】:How to combine intersection and union types如何组合交集和联合类型
【发布时间】:2017-12-18 22:27:15
【问题描述】:

需要通过属性c“扩展”基本类型Base。 以下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 添加到工会的两个成员之外,还有其他解决方案吗?谢谢!

【问题讨论】:

    标签: ecmascript-6 flowtype


    【解决方案1】:

    您可以反转这一点,使 Derived 成为 BaseABaseB 的并集,并为两个基添加具有交集的公共属性 (working example):

    /* @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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2018-10-26
      • 2018-07-29
      • 1970-01-01
      • 2020-07-31
      • 2021-09-03
      • 2019-11-14
      • 2020-05-21
      • 2010-10-28
      相关资源
      最近更新 更多