Using union of array types leads to error in type definition #7390
Open
Description
// @flow
type ColumnDef = {|
type: 'column',
|};
type GroupDef = {|
type: 'group'
|};
type ColumnOrGroupArrayDef = Array<ColumnDef> | Array<GroupDef>;
// Bug?
let arr: ColumnOrGroupArrayDef = ([{type: 'group'}]: Array<GroupDef>);
arr.reduce((accum, x) => accum + String(x.type), '') // commenting out this line will stop the error on line 11!
// Question: Can I refine a ColumnOrGroupArrayDef?
if (arr[0] && arr[0].type === 'group') {
(arr: Array<GroupDef>).reduce((accum, x) => accum + String(x.type), '') // Error
}
I have a type that can either be an array of columns or an array of groups. There are some situations where I can treat both in the same way, and others where I need to refine which array I'm using. It seems reasonable that I'd need to refine or cast the array before using it, but I'm not sure how to do that.
The bug I noticed is this: a variable typed to be a union of array types, when used in a non-type-safe way, produces an error in the type definition. This makes it fairly difficult to debug.