简体   繁体   中英

flow types, casting to array type doesn't work from explicit type, but does from implicit type

Considering the following lines

const a: Array<number> = [1,2,3];
const b = [1,2,3];
const q: Array<boolean | number> = a;
const r: Array<boolean | number> = b;

The above code works for lines 2 & 4 ( b and r ), however flow chokes on line 3, with the error:

Cannot assign a to q because number [1] is incompatible with boolean [2] in array element.

This makes little sense to me, especially since the line below does work. Why does this not work, and how can I make it work?


As for an application of above: in my real working code I have a function that accepts any "simple javascript object" (an object without functions). Which I described by:

 type primitive = boolean | number | string | void; type plain_js_object = { [string]: (primitive | Array<primitive> | plain_js_object) } function theFunction(input: plain_js_object) { //do_things return JSON.stringify(input); } 

And then I have some other function that returns an array of integers, the function is then called like:

 const fib = [1, 1, 2, 3, 5]; theFunction({sequence: fib}); 

Obviously {sequence: fib} is a of type {sequence: Array<number>} which is obviously a subtype of the plain javascript objects.

I think some helpful info can be found about $ReadOnlyArray . The issue (I think) is that Array is invariant, meaning Array<number> is not a subtype of Array<number | boolean> Array<number | boolean> . This works fine:

const a: Array<number> = [1,2,3];
const b = [1,2,3];
const q: $ReadOnlyArray<boolean | number> = a;
const r: Array<boolean | number> = b;

My best guess is that Flow does something smart when the type is inferred from an array literal rather than explicitly typed.

As for your example, I didn't get any flow errors running 0.93, can you show a repro in a Flow Try link or something?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM