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

A spread argument must either have a tuple type or be passed to a rest parameter

I am new to TypeScript and I am going to change my project to TypeScript.
But I got some error.
I have searched about the spread arguments but I can’t figure it out correctly.

This is I tried so far.

export const fetcher = async (...args) => {
    return fetch(...args).then(async (res) => {
        let payload;
        try {
            if (res.status === 204) return null; // 204 does not have body
            payload = await res.json();
        } catch (e) {
            /* noop */
        }
        if (res.ok) {
            return payload;
        } else {
            return Promise.reject(payload.error || new Error('Something went wrong'));
        }
    });
};

But it throws an error like this line:

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

return fetch(...args).then(async (res) => {

A spread argument must either have a tuple type or be passed to a rest parameter

>Solution :

You did not give args a type. Because it is a spread argument, TypeScript automatically types it as any[].

In JavaScript, you can spread an array into the arguments of a function call. This is called a spread argument. To make this type-safe, the type of the array you are spreading must be a tuple type. any is normally seen as an escape hatch which disables type checking. But spread arguments are an exception where even any is not allowed.

The signature of fetch looks like this:

function fetch(input: RequestInfo | URL, init?: RequestInit | undefined)

If you want to pass an array (in this case args) via spread argument, the tuple type of args must then look like this:

args: [input: RequestInfo | URL, init?: RequestInit | undefined]

Because we are lazy and don’t want to type this out by hand, we can use the Parameters utility type. We can pass typeof fetch to Parameters and it will return the tuple type of the parameters of fetch for us.

export const fetcher = async (...args: Parameters<typeof fetch>) => 

Playground

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