【问题标题】:Custom type is incompatible with mixed自定义类型与混合不兼容
【发布时间】:2018-03-26 23:32:56
【问题描述】:

问题可以demo'd here

我想定义一个可以接受混合类型数组的函数:

function foo(x: Array<mixed>): string {
  // ... do something
}

然后我尝试使用一些自定义对象类型的数组来调用它:

type Thing = {
  id: string
}

let array : Array<Thing> = [{id: 'hello'}];

foo(array);

...我收到以下错误

Cannot call `foo` with `array` bound to `x` because `Thing` [1] is incompatible with mixed [2] in array element.`

关于mixed 类型有什么我不理解的地方吗?为什么不能使用对象数组作为参数?

【问题讨论】:

标签: flowtype


【解决方案1】:

这与数组参数的可变性有关。您可以使用$ReadOnlyArray 来满足要求。

function foo(x: $ReadOnlyArray<mixed>): string {
  // ... do something
  return "hello";
}

type Thing = {
  id: string
}

let array : Array<Thing> = [{id: 'hello'}];

foo(array);

数组是通过引用而不是值传递的,因此变量array 中包含的值可以在foo 中修改。例如

x.push(1)

array 将不再是仅包含 Thing 的数组。所以使用 $ReadOnlyArray 意味着x 是不可变的,因此array 是安全的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2015-11-09
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多