2016-12-02 13 views
1

Ich habe einige JSON-Typen aus the Flow docs gestohlen."Subtype" ist nicht kompatibel mit Union-Typ

Ich gebe ein Array von Zeichenfolgen - mit der Anmerkung Array<string> - an eine Funktion, die ein Versprechen mit einigen JSON - annotiert Promise<JSON> ausgibt. Der Typ JSON scheint jedoch mit Array<string> inkompatibel zu sein.

Wie ich es verstehe, sollte die oben kompatibel sein, da JSONJSONArray sein könnte, die Array<JSON> ist, wo JSONstring sein könnte.

Ich machte ein einfacheres Beispiel als das in meinem Code, und die letzte Zeile wirft den gleichen Fehler. Sie können es in Aktion sehen here

// @flow 

type JSON = string | number | boolean | null | JSONObject | JSONArray 
type JSONObject = { [key: string]: JSON } 
type JSONArray = Array<JSON> 

const stringArrayWithArrayAnnotation : Array<string> = ["foo"] 

// Line below throws: 
// array type 
// This type is incompatible with 
// union: string | number | boolean | null | JSONObject | JSONArray` 
const stringArrayWithJSONAnnotation : JSON = stringArrayWithArrayAnnotation 

Antwort

3

Array Typ ist invariant docs: Array elements

type A = Array<number | string>; 
declare var x: Array<string>; 
const y: A = x // => error: number. This type is incompatible with string 

so während string ein Subtyp von number | string ist, Array<string> ist nicht ein Subtyp von Array<number | string>