2017-07-13 4 views
1

Sie müssen den Basistyp Base durch die Eigenschaft c erweitern. Folgende code:Kombinieren von Schnittstellentypen und Unionstypen

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

Ergebnisse von

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 

Gibt es eine Lösung als andere die gleiche prop c auf beide Mitglied der Vereinigung hinzufügen? Vielen Dank!

Antwort

1

Sie können dies umkehren und Derived die Vereinigung von BaseA und BaseB machen und das gemeinsame Attribut mit einer Schnittstelle für beide der Basen hinzufügen (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; 
    } 
} 
Verwandte Themen