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);
CodePudding user response:
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];