2016-12-02 32 views
1

我从the Flow docs盗取了一些JSON类型。“子类型”与工会类型不兼容

我输入一个字符串数组 - 注释Array<string> - 输出带有一些JSON的承诺的函数 - 带注释的Promise<JSON>。但是,JSON类型似乎与Array<string>不兼容。

据我了解,上面应该是兼容的,因为JSON可能是JSONArrayArray<JSON>,其中JSON可能是string

我做了一个比我的代码更简单的例子,最后一行抛出相同的错误。你可以看到它在行动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 

回答

3

Array类型是不变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 

因此而stringnumber | string一个亚型,Array<string>Array<number | string>

亚型