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

typescript error when spreading `Parameters<F>`

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?

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 :

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

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