我从 the Flow docs 中窃取了一些 JSON 类型.
我输入了一个字符串数组 - 注释 Array<string>
- 到一个输出带有一些 JSON 的 promise 的函数 - 注释 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>
的子类型
关于javascript - "Subtype"与联合类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934396/