I have a situation, where I call a function with some arguments, which are resolved using another function.
This is how the code looks.
function getArgs (): [string, number] {
return ['hello world', 22]
}
function callFnWithArgs (callback) {
callback(...getArgs())
}
callFnWithArgs(function (/* typehint here */) {
})
callFnWithArgs takes a callback and then execute it by passing some arguments.getArgs().So, is there any way to type hint, the arguments of the callback, which is the return value of another function?
In TypeScript 3.0 or newer, you can use the ReturnType type alias from the standard library to determine the return type of getArgs and then use a rest parameter to tie that to the callback of 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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With