获取typescript中的最后一个函数参数

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

我正在尝试构造一个函数的参数,该函数只关心传入的最后一个参数,将其值绑定到变量next;以下在普通js,节点10中正常工作:

> function f(...{length, [length - 1]: next}) { console.log(next) }
> f(1,2,3,4)
4

然而,打字稿中的相同构造给了我:

error TS2501: A rest element cannot contain a binding pattern.

function (...{length, [length - 1]: next}) {
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我怎样才能解决这个问题?

node.js typescript destructuring
1个回答
1
投票

非常有趣的问题,因为基本上语句 - “TS是JS的超集”在这里不起作用。

事实证明,当我们尝试在解构和扩展运算符的同时使用绑定模式时,我们会收到错误:

enter image description here

目前在TS诊断消息文件中,A_rest_element_cannot_contain_a_binding_pattern_2501存在明显错误

还有一个open Pull Request和TypeScript repo可能会解决这个“问题”(不确定这是一个问题或其他)。

但是你总是可以为你的任务选择这种方法:

function f(...args) {
    console.log(args[args.length - 1]);
}
© www.soinside.com 2019 - 2024. All rights reserved.