Reputation: 4639
I have a function that is used in a lot of different places, so it has a very broad typing:
export const stringToArrayFn = (
accessor?:
| Function
| string
| boolean
| Object
| Array<Function | string | boolean | Object>,
defaultAccessor?: Function,
raw?: boolean
)
When I call it:
stringToArrayFn(yAccessor)
With yAccessor being typed as:
yAccessor?: Array<Function | string> | Function | string
Flow complains Cannot call stringToArrayFn with yAccessor bound to accessor because boolean [1] is incompatible with
string [2] in array element.
I don't get it because the Array in yAccessor is a valid subset of the array possibilities defined in stringToArrayFn (the former only allows arrays of function or string, the latter allows arrays of functions, strings, bools and objects).
How does one handle this kind of typing?
Upvotes: 2
Views: 219
Reputation: 220954
stringToArrayFn
could call accessor.push(true)
and cause your Array<Function | string>
to contain a boolean
, which would be bad.
Use $ReadOnlyArray
instead of Array
in the definition of stringToArrayFn
if it doesn't intend to mutate the provided array.
Upvotes: 4