【问题标题】:"Subtype" is incompatible with union type“子类型”与联合类型不兼容
【发布时间】:2016-12-03 00:41:43
【问题描述】:

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

【问题讨论】:

    标签: javascript types flowtype


    【解决方案1】:

    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&lt;string&gt; 不是 Array&lt;number | string&gt; 的子类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 2019-04-02
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多