2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.