javascript - "Subtype"与联合类型不兼容

标签 javascript types flowtype

我从 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

所以 stringnumber | string 的子类型, Array<string> 不是 Array<number | string> 的子类型

关于javascript - "Subtype"与联合类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934396/

相关文章:

javascript - IE中的ContextMenu获取当前打开的浏览器url

javascript - 如何使用 pdfmake 在文本行末尾添加图像?

javascript - IndexedDB 和 Angular 应用程序上的大量插入

HTML5 中的纯 JavaScript 链接

javascript - 如何使用采用接口(interface)实现类作为参数的方法编写 Flow 接口(interface)?

javascript - 流: HTMLVideoElement and HTMLElement

javascript - 流量: Simpler way to annotate `type | typeof undefined` ?

MySQL固定长度和可变长度数据类型

scala - 类似元组类型的递归类型

java - 为什么instanceof不像听起来那样工作?