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

How to determine type of callback's input parameters in typescript

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…

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

>Solution :

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.

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