【问题标题】:Get the last function argument in typescript获取打字稿中的最后一个函数参数
【发布时间】:2018-09-08 06:26:49
【问题描述】:

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

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

但是 typescript 中的相同结构给了我:

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

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

我该如何解决这个问题?

【问题讨论】:

    标签: node.js typescript destructuring


    【解决方案1】:

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

    事实证明,当我们尝试同时在析构和扩展运算符中使用绑定模式时,我们会得到一个错误:

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

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

    但您始终可以为您的任务选择这种方法:

    function f(...args) {
        console.log(args[args.length - 1]);
    }
    

    【讨论】:

    • fwiw, (...args) => {const {length, [length - 1]: next} = args} 编译得很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多