1

I have an function:

const myFunc = (callback: (...params: any) => void, params: [any]): void => {
   callback(...params);
};
//sample of using
myFunc((name: string) => { console.log(name) }, ["Mark"])

The myFunc takes callback and parameters. How to avoid "any" and provide that params in both case have same type? p.s. (callback: (...params: T) => void, params: [T]) = doesn't work...

2
  • Do all parameters have the same type? Do you expect the same number of parameters? Commented May 31, 2022 at 3:19
  • yes - all parameters will have same type, number of parameters can by dynamic. Commented May 31, 2022 at 3:24

1 Answer 1

1

You can use a variadic tuple type:

const myFunc = <T extends unknown[]>(
  callback: (...params: T) => void,
  params: T
): void => {
   callback(...params);
};

myFunc((name: string) => {}, ["Mark"]); // OK
myFunc((name: string, age: number) => {}, ["Mark", 23]); // OK

myFunc((name: string) => {}, ["Mark", 23]); // Error
myFunc((name: string, city: string) => {}, ["Mark", 23]); // Error

If you know all parameters to be of the same type, you can use that type (e.g. string) instead of unknown.

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.