Ama*_*irk 6 typescript typescript3.0
我遇到一种情况,我调用一个带有一些参数的函数,这些参数是使用另一个函数解析的。
这就是代码的样子。
function getArgs (): [string, number] {
return ['hello world', 22]
}
function callFnWithArgs (callback) {
callback(...getArgs())
}
callFnWithArgs(function (/* typehint here */) {
})
Run Code Online (Sandbox Code Playgroud)
callFnWithArgs接受回调,然后通过传递一些参数来执行它。getArgs()。那么,有没有办法输入提示,即回调的参数,即另一个函数的返回值?
在 TypeScript 3.0 或更高版本中,您可以使用ReturnType标准库中的类型别名来确定 的返回类型getArgs,然后使用剩余参数将其绑定到 的回调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
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9069 次 |
| 最近记录: |