Issue
How to concat array of the union type in typescript?
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 simplify the problem and remove the red herring by trying the following code 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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.