Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to wrap a function and retain its types?

Tags:

typescript

I'm trying to create a generic wrapper function which will wrap any function passed to it.

At the very basic the wrapper function would look something like

function wrap<T extends Function>(fn: T) {     return (...args) => {         return fn(...args)     }; } 

I'm trying to use it like:

function foo(a: string, b: number): [string, number] {     return [a, b]; }  const wrappedFoo = wrap(foo); 

Right now wrappedFoo is getting a type of (...args: any[]) => any

Is it possible to get wrappedFoo to mimic the types of the function its wrapping?

like image 513
tikotzky Avatar asked Jul 26 '16 19:07

tikotzky


People also ask

What does wrapping a function mean?

A wrapper function is a subroutine (another word for a function) in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation.

What can be used to wrap a function with another function?

wrap() is used to wrap a function inside other function. It means that the first calling function (a function which is calling another function in its body) is called and then the called function is being executed. If the calling function does not call the called function then the second function will not be executed.

What is a function wrapper R?

As the name implies, a wrapper function is just a function which wraps another function. Maybe inside it does something like set some default values for parameters, etc.


1 Answers

This works with any number of arguments, and keep all the arguments & return types

const wrap = <T extends Array<any>, U>(fn: (...args: T) => U) => {   return (...args: T): U => fn(...args) } 
like image 143
foray1010 Avatar answered Sep 21 '22 17:09

foray1010