TypeScript 错误数组与 Ramda 的多维组合

问题描述 投票:0回答:2

我写了一个小函数来执行数组元素的多维组合。示例:

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"]],
    ]
  )
})

该函数按预期工作,但如果我不使用

// @ts-ignore
,我会收到以下 TypeScript 错误,代码如下:

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

您的帮助将不胜感激。

typescript ramda.js
2个回答
0
投票

Ramda 有

R.xprod
函数,它可以做同样的事情。这对于 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>


0
投票

您遇到的 TypeScript 错误表明 TypeScript 无法推断传递给组合函数的参数的正确类型。为了解决这个问题,您可以提供类型注释来帮助 TypeScript 理解输入数组的结构。

您可以定义类型别名或接口来描述多维数组的结构。具体方法如下:

type MultiDimensionalArray<T> = Array<T | MultiDimensionalArray<T>>;

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

通过此设置,TypeScript 将识别 arr 是一个多维数组,其中每个元素可以是 T 类型,也可以是相同类型的另一个多维数组。这应该可以解决 TypeScript 错误,而无需使用 // @ts-ignore。

确保根据您期望的数组元素类型调整类型 T。如果您知道您的组合函数将使用的元素的特定类型,您可以将unknown替换为这些类型以进行更精确的类型检查。

© www.soinside.com 2019 - 2024. All rights reserved.