gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:46:03 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com