Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – pass a function and its arguments to another function & enforce number and types of args

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...args: typeof arguments of f

Which is obviously not valid Typescript.

How can I write typescript code that does that?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading