gpt4 book ai didi

使用函数解析的 Typescript 回调参数

转载 作者:行者123 更新时间:2023-12-03 22:14:19 24 4
gpt4 key购买 nike

我有一种情况,我调用一个带有一些参数的函数,这些参数是使用另一个函数解决的。

这就是代码的样子。

function getArgs (): [string, number] {
return ['hello world', 22]
}

function callFnWithArgs (callback) {
callback(...getArgs())
}

callFnWithArgs(function (/* typehint here */) {
})
  • 函数callFnWithArgs接受一个回调,然后通过传递一些参数来执行它。
  • 这些参数由另一个名为 getArgs() 的函数给出。 .

  • 那么,有没有办法输入hint,回调的参数,也就是另一个函数的返回值?

    最佳答案

    在 TypeScript 3.0 或更新版本中,您可以使用 ReturnType来自标准库的类型别名来确定 getArgs 的返回类型然后使用 rest 参数将其与 callFnWithArgs 的回调联系起来:

    function getArgs (): [string, number] {
    return ['hello world', 22]
    }

    function callFnWithArgs (callback: (...args: ReturnType<typeof getArgs>) => void) {
    callback(...getArgs())
    }

    callFnWithArgs(function (a, b) {
    // a is string, b is number
    })

    关于使用函数解析的 Typescript 回调参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001593/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com