TypeScript error multi-dimensional combination of arrays with Ramda

35 Views Asked by At

I wrote a small function to perform multi-dimensional combination of array elements. Example:

test('combine', () => {
  const result = combine([[[1, 2], [3, 4]], [['a', 'b'], ['c', 'd']]])
  expect(result).toStrictEqual([
      [[ 1, 2], ["a", "b"]],
      [[ 1, 2], ["c", "d"]],
      [[ 3, 4], ["a", "b"]],
      [[ 3, 4], ["c", "d"]],
    ]
  )
})

The function works as expected but if I don't use // @ts-ignore I get the following TypeScript error with the following code:

export const combine = (arr: Array<unknown>) => R.apply(R.liftN(arr.length, (...args) => args), arr)

TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'unknown[]' is not assignable to parameter of type '[]'.
      Target allows only 0 element(s) but source may have more.
     7 |
  >  8 | export const combine = (arr: Array<unknown>) => R.apply(R.liftN(arr.length, (...args) => args), arr)
       |                                                                                                 ^^^

Your help will be appreciated.

1

There are 1 best solutions below

1
Ori Drori On

Ramda has the R.xprod function, which does the same thing. This also works out of the box with TS.

const combine = R.apply(R.xprod)

const result = combine([[[1, 2], [3, 4]], [['a', 'b'], ['c', 'd']]])

console.log(JSON.stringify(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.29.1/ramda.min.js" integrity="sha512-PVSAmDFNqey8GMII8s9rjjkCFvUgzfsfi8FCRxQa3TkPZfdjCIUM+6eAcHIFrLfW5CTFAwAYS4pzl7FFC/KE7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>