“这个表达式是不可调用的。联合类型的每个成员......都有签名,但这些签名中没有一个是相互兼容的。”为什么?

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

This expression is not callable. Each member of the union type '{ (...items: ConcatArray<{...}>[]): { ... }[]; (...items: ({ ... } | ConcatArray<{ ...; }>)[]): { ...; }[]; } | { ...; }' has signatures, but none of those signatures are compatible with each other.

代码沙盒: 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);
stack overflow "This expression is not callable. Each member of the union type... has signatures, but none of those signatures are compatible with each other." Why?
原文答案
author avatar

接受的答案

您正在跟随红鲱鱼。您的问题具有 **nothing to do with** “联合类型的数组”。问题是您要尝试 **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

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

@jsejcksn recommends ,“使用sprain语法结合数组”,“请参阅 tsplay.dev/wOzdRW ”。这使您可以使用混合元素类型来对抗数组:

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

答案: