I’m encountering an issue while trying to implement a TypeScript function that accepts a generic function and its parameters. Here’s a simplified version of my code:
type Fns = {
fn1: () => string;
fn2: (param1: string) => string;
fn3: (param1: string, param2: string) => string;
};
const myFn = <T extends keyof Fns>(
someThingElse: boolean,
fn: Fns[T],
...args: Parameters<Fns[T]>
): string => {
if (someThingElse) return "something";
return fn(...args);
};
myFn(true, () => "hello"); // something
myFn(false, () => "hello"); // hello
myFn(false, (a: string) => a + " world", "hello"); // hello world
myFn(false, (a: string, b: string) => a + " " + b, "hello", "john"); // hello john
The error message I’m receiving is:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
I understand that TypeScript is expecting a tuple type or rest parameter for args, but I’m not sure how to resolve this in the context of a generic function that can accept varying numbers of parameters depending on the function type (fn).
I have tried making a simpler version:
const myFn = (
fn: fn1 | fn2 | fn3,
...args: Parameters<fn1 | fn2 | fn3>
): string => {
return fn(...args);
};
But this one receives the same error.
kevinvu184 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.