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

0

Issue

When I try to use concat with the array of union type, I got this error:

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.

CodeSandbox: https://codesandbox.io/s/modern-breeze-qt9mb?file=/src/index.ts

Code example:

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);

Solution

You are following a red herring. Your problem has nothing to do with "arrays of the union type". The problem is that all of the arrays you are trying to concat have elements of different types, and concat requires that the arrays have elements of the same type T:

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

The above is from lib.es5.d.ts.

You can quickly quickly simplify the problem and discard the red herring with this test and understanding the error messages:

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

You original error message was also telling you this: "Each member of the union type… has signatures, but none of those signatures are compatible with each other."

As @jsejcksn recommends, "Use spread syntax to combine the arrays", "See tsplay.dev/wOzdRW". This allows you to concat arrays with mixed element types:

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

Answered By – Inigo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More