Home > Blockchain >  Typescript - pass a function and its arguments to another function & enforce number and types of arg
Typescript - pass a function and its arguments to another function & enforce number and types of arg

Time:03-23

I want to define a function that gets as parameters another function f and its arguments args, and I want Typescript to make sure that the passed arguments are correct for the passed function.

Pseudo code

function A (n: number, s: string, b: boolean) {
  ...
}

function B (f: Function, ...args: typeof arguments of f) {
  ...
  f(args)
}

B(A, 1, 'str', true) // typescript is happy
B(A, 1, 'str') // typescript is sad
B(A, 1, undefined, true) // typescript is sad
// any other example of wrong arguments of A passed to b would raise Typescript error...

So the important part here is this:

...args: typeof arguments of f

Which is obviously not valid Typescript.

How can I write typescript code that does that?

CodePudding user response:

Can do that using the Parameters utility type.

For example...

function B<T extends (...args: any) => any> (f: T, ...args: Parameters<T>) {
  f(args)
}

Here is a playground showing the errors you are expecting.

Note that this checking is compile time only and will not provide any runtime protection after the TypeScript is compiles to JavaScript. If you need runtime protection you need to use the arguments object and write some custom code to verify number and types of arguments passed. Something like this.

  • Related