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

Time:05-31

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...

CodePudding user response:

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.

  • Related