I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript:
const arr = [1, 2, 3];
arr.reduce((all, cur) => [
...(all instanceof Array ? all : [all]),
0,
cur
])
During the first iteration, the all
variable contains the first item and is of type number
, but in subsequent iterations it becomes a list. This can be observed by logging output:
arr.reduce((all, cur) => {
console.log(all);
return [
...(all instanceof Array ? all : [all]),
0,
cur
]
});
// 1
// [1, 0, 2]
// [1, 0, 2, 0, 3]
This method works perfectly in pure JavaScript, however, there seems to be an issue when applying TypeScript for typing purposes:
arr.reduce((all: number | number[], cur: number) => [
...(all instanceof Array ? all : [all]),
0,
cur
]);
... which results in the following error:
TS2345: Argument of type '(all: number | number[], cur: number) => number[]' is not assignable to parameter of type '(previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number'. Type 'number[]' is not assignable to type 'number'.
Is there a different approach that could be used to achieve the same result while utilizing TypeScript?