"This expression is not callable. Each member of the union type... has signatures, but none of those signatures are compatible with each other." 为什么?

"This expression is not callable. Each member of the union type... has signatures, but none of those signatures are compatible with each other." Why?

当我尝试将 concat 与联合类型数组一起使用时,出现此错误:

这个表达式是不可调用的。联合类型的每个成员 '{ (...items: ConcatArray<{...}>[]): { ... }[]; (...项目: ({ ... } | ConcatArray<{ ...; }>)[]): { ...; }[]; } | { ...; }' 有签名,但是 none 个签名相互兼容。

代码沙箱:https://codesandbox.io/s/modern-breeze-qt9mb?file=/src/index.ts

代码示例:

const arr1 = [
  { val1: 1, val2: 2, val3: 3 },
  { val1: 11, val2: 22, val3: 33 }
];

const arr2 = [
  { val1a: "1a", val2a: "2a", val3a: "3a" },
  { val1a: "11a", val2a: "22a", val3a: "33a" }
];

const arr3 = [
  { foo: "lfsfs", bar: "fabgg" },
  { foo: "l414g", bar: "fahrh" }
];

function getRandomArr() {
  if (Math.random() < 0.5) {
    return arr2;
  } else {
    return arr1;
  }
}
//error
const FinalArr = getRandomArr().concat(arr3);

你在跟踪一个转移注意力的人。您的问题“联合类型的数组”无关。问题是 all 您尝试 concat 的数组具有不同类型的元素,并且 concat 需要数组具有相同类型的元素 T:

Array<T> {
    concat(...items: ConcatArray<T>[]): T[];
    concat(...items: (T | ConcatArray<T>)[]): T[];
}

以上来自lib.es5.d.ts.

您可以通过尝试以下代码并理解错误消息来快速简化问题并消除歧义:

const a = arr1.concat(arr3)   // error
const b = arr2.concat(arr3)   // error

您最初的错误消息还告诉您:“联合类型的每个成员...都有签名,但这些签名中的 none 彼此兼容。”

As , "Use spread syntax to combine the arrays", "See tsplay.dev/wOzdRW”。这允许您连接具有混合元素类型的数组:

const FinalArr = [...getRandomArr(), ...arr3];