typescript error when spreading `Parameters<F>`

16 Views Asked by At

This is the narrowed down code from my actual use case.

function wrapMe<F extends (...args: any) => any>(
    f: F,
): (...args: Parameters<F>) => ReturnType<F> {
    return function(...args: Parameters<F>): ReturnType<F> {
        return f(...args);
        //          ^^^^
        // Type 'Parameters<F>' must have a '[Symbol.iterator]()' method that returns an iterator. [2488]
    }
}

Why is this a typescript error?

1

There are 1 best solutions below

0
jcalz On BEST ANSWER

This is a known bug in TypeScript, as described in microsoft/TypeScript#36874. Until and unless it's resolved, you can work around it either by changing the constraint to make the parameter any[] instead of any:

function wrapMe<F extends (...args: any[]) => any>(
  // -----------------------------> ^^^^^
    f: F,
): (...args: Parameters<F>) => ReturnType<F> {
    return function (...args: Parameters<F>): ReturnType<F> {
        return f(...args);
    }
}

or by wrapping Parameters<T> in a variadic tuple:

function wrapMe<F extends (...args: any) => any>(
    f: F,
): (...args: Parameters<F>) => ReturnType<F> {
    return function (...args: [...Parameters<F>]): ReturnType<F> {
    // ---------------------> ^^^^^^^^^^^^^^^^^^
        return f(...args);
    }
}

Playground link to code