Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript callback arguments, which are resolved using a function

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 */) {
})
  1. The function callFnWithArgs takes a callback and then execute it by passing some arguments.
  2. Those arguments are given by another function called getArgs().

So, is there any way to type hint, the arguments of the callback, which is the return value of another function?

like image 238
Aman Virk Avatar asked Aug 24 '18 09:08

Aman Virk


1 Answers

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
})
like image 176
Matt McCutchen Avatar answered Oct 02 '22 20:10

Matt McCutchen