dontexist
dontexist

Reputation: 5642

"Subtype" is incompatible with union type

I stole some JSON types from the Flow docs.

I input an array of strings - annotated Array<string> - to a function that outputs a promise with some JSON - annotated Promise<JSON>. However, the JSON type seems to be incompatible with Array<string>.

As I understand it, the above should be compatible, since JSON could be JSONArray which is Array<JSON>, where JSON could be string.

I made a simpler example than the one in my code, and the last line throws the same error. You can see it in action 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

Upvotes: 1

Views: 403

Answers (1)

gcanti
gcanti

Reputation: 1462

Array type is invariant 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

so while string is a subtype of number | string, Array<string> is not a subtype of Array<number | string>

Upvotes: 4

Related Questions