[SOLVED] 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) {

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?


Can do that using the Parameters utility type.

For example…

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

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.

Answered By – dezfowler

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *