为什么此ES6函数有此Typescript错误,我该怎么办?

时间:2019-07-29 09:31:43

标签: javascript typescript

我正在VSCode和此行中运行Typescript

const Felix_Reverse = ([h, ...r]) => r.length > 0 && Felix_Reverse(r) + h || h;

在嵌入的Felix_Reverse调用的突出显示中,使用r参数抛出以下错误

Argument of type 'any[]' is not assignable to parameter of type '[any, ...any[]]'. 
    Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'.

这是什么意思,我应该如何正确注释该功能?

2 个答案:

答案 0 :(得分:3)

您需要指定参数类型和返回类型:

const Felix_Reverse = ([h, ...r]: number[]): number =>
  r.length > 0 && Felix_Reverse(r) + h || h;

在这种情况下,h的类型为numberr的类型为number[]

答案 1 :(得分:1)

这里的潜在问题是数组解构有两个不同的目的:一个是像元组那样传递值(例如React从useState返回这样的元组),另一方面,它用于访问特定部分像你一样做数组。 Typescript必须正确输入两个目的,这就是为什么它默认将数组解构参数键入为元组类型的原因:

  const Felix_Reverse = ([t, ...h]: [any, ...any[]]) => /*...*/;

一方面很棒,因为它可以防止:

  Felix_Reverse([])

因为这不能完全填充元组类型(因为它必须具有类型any的第一项)。这就是TS抱怨的问题,它说Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'.,或者换句话说:它不能保证递归调用至少包含一个元素(实际上可以,因为r.length > 0可以,但是编译器不是)还不是那么聪明)。

现在要解决这个问题,我们必须将元组类型转换为数组类型。通过该操作,甚至可以传递空数组,但是t可能是undefined

 const Felix_Reverse = ([h, ...r]: string[] | number[]) => r.length > 0 && Felix_Reverse(r) + h || h;