Ecmascript 6 如何组合相交类型和并集类型
需要通过属性Ecmascript 6 如何组合相交类型和并集类型,ecmascript-6,flowtype,Ecmascript 6,Flowtype,需要通过属性c来“扩展”基类型base。 以下是: 结果由 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 cann
c
来“扩展”基类型base
。
以下是:
结果由
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
添加到工会的两个成员之外,还有其他解决方案吗?谢谢 您可以将其反转,使派生的成为BaseA
和BaseB
的并集,并为两个基添加具有交集的公共属性():
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
/* @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;
}
}