"Subtype" 与联合类型不兼容
"Subtype" is incompatible with union type
我从 the Flow docs 偷了一些 JSON 类型。
我输入了一个字符串数组 - 注释为 Array<string>
- 到一个函数,该函数输出带有一些 JSON 的承诺 - 注释为 Promise<JSON>
。但是,JSON
类型似乎与 Array<string>
.
不兼容
据我了解,以上应该是兼容的,因为 JSON
可能是 JSONArray
即 Array<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
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
所以虽然 string
是 number | string
的子类型,但 Array<string>
是 而不是 Array<number | string>
[=17 的子类型=]
我从 the Flow docs 偷了一些 JSON 类型。
我输入了一个字符串数组 - 注释为 Array<string>
- 到一个函数,该函数输出带有一些 JSON 的承诺 - 注释为 Promise<JSON>
。但是,JSON
类型似乎与 Array<string>
.
据我了解,以上应该是兼容的,因为 JSON
可能是 JSONArray
即 Array<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
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
所以虽然 string
是 number | string
的子类型,但 Array<string>
是 而不是 Array<number | string>
[=17 的子类型=]