Reputation: 22478
The problem can be demo'd here
I want to define a function that can take an array of mixed types:
function foo(x: Array<mixed>): string {
// ... do something
}
Then I try to call it with an array off some custom object type:
type Thing = {
id: string
}
let array : Array<Thing> = [{id: 'hello'}];
foo(array);
... and I get the following error
Cannot call `foo` with `array` bound to `x` because `Thing` [1] is incompatible with mixed [2] in array element.`
Is there something that I'm not understanding about the mixed
type. Why can't a use an array of objects as an argument?
Upvotes: 1
Views: 1364
Reputation: 3201
It has to do with a mutability of the array argument. You can use $ReadOnlyArray
to satisfy the requirement.
function foo(x: $ReadOnlyArray<mixed>): string {
// ... do something
return "hello";
}
type Thing = {
id: string
}
let array : Array<Thing> = [{id: 'hello'}];
foo(array);
Array's are passed by reference, not by value, so the value contained in the variable array
can be modified within foo
. e.g.
x.push(1)
array
would no longer be an array of Thing
only. So using $ReadOnlyArray means that x
is immutable and therefore array
is safe.
Upvotes: 3