To utilize a spread argument, it is essential for it to either be in tuple form or be supplied to a rest

I am currently learning TypeScript and working on converting my project to TypeScript. However, I encountered an error while trying to use spread arguments. I have researched this topic, but I am still unsure of the correct usage.

Here is my current approach:

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'));
        }
    });
};

However, I am encountering an error on this line:

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

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

Answer №1

Failure to specify a type for the args parameter results in TypeScript automatically assigning it the type any[] due to it being a spread argument.

In the realm of JavaScript, you have the ability to spread an array as arguments in a function call, referred to as a spread argument. To ensure type safety in this scenario, the array being spread must be of a tuple type. It's worth noting that while any is often considered a means to bypass type checking, spread arguments are an exception where the use of any is not permitted.

The syntax for the fetch function resembles the following:

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

If your intention is to pass an array (such as args) via a spread argument, the tuple type for args should be defined as follows:

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

To avoid manual typing and for convenience, you can utilize the Parameters utility type. Simply pass typeof fetch to Parameters, and it will return the tuple type of the parameters of fetch automatically.

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

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Vue Component Unable to Locate Property

Just dipping my toes into Vue with a simple test implementation and running into some trouble breaking down data into components. Let's take a closer look at the code: <body> <header id="main-header"> <custom-header></ ...

"Encountering errors during npm installation due to a failed preinstall

Having identified security vulnerabilities for knexnest > knex > minimist, I encountered an issue where the minimist version did not update using npm audit fix or a simple npm update. Following the steps outlined in this informative article resolved ...

getStaticProps only runs on IIS after the entire page is refreshed

Using the nextjs getStaticProps feature in my project has been smooth sailing so far. However, after uploading the Static files to IIS, the feature seemed to stop working until I configured a urlRewrite module on it. I noticed that when initially visiting ...

Enhancing Plotly Graphs with Custom Node Values

Encountering an issue while attempting to assign values to nodes on a plotly graph. Code: <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <style> .graph-container { ...

Warnings from Webpack may appear while running the Next.js development server

Encountering these warnings when running npm dev: <w> [webpack.cache.PackFileCacheStrategy] Restoring pack from /Users/pdeva/code/monorepo/web/app/.next/cache/webpack/client-development.pack failed: TypeError: Cannot read properties of undefined (rea ...

Simulating npm package with varied outputs

In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another. To achieve this, I hav ...

What is the best way to assign an active class to a specific footer ID on an HTML page using AngularJS?

I tried using the activeLink directive to apply an active class to a specific id on the page, but it didn't work as expected. .directive('activeLink', ['$location', function (location) { return { restrict: 'A', ...

Unable to accept the link ID in the modal

Presently, I am facing an issue with a modal that links a product with a customer and involves product discount calculations. The customer is automatically selected using the modal id, and the product is chosen through select options with a while loop. T ...

Oops! An error occurred when attempting to log in with an unidentified authentication method called "local"

After following a tutorial to build my project, I encountered an issue with the login functionality. While the signup process works fine, attempting to log in a registered user using postman results in the error: Error: Unknown authentication strategy "loc ...

What is preventing the MenuItem component from functioning as a Link in React Material-UI?

Hey there! I've been trying to implement a popover menu that changes the URL and component after clicking on an item, but unfortunately it's not working as expected. I created a setup in this sandbox: https://codesandbox.io/s/romantic-surf-40p19? ...

Implementing Vue plugins in your Store: A step-by-step guide

Looking for the proper way to integrate a plugin within a Vuex module or plain JS module. Currently using an event bus but unsure if it's the best approach. Any guidance would be appreciated. Plugin1.plugin.js: const Plugin1 = { install(Vue, optio ...

Retrieving the value of a selected option in Angular

I have the following dropdown select in my HTML and I am currently retrieving the text content of the selected option. How can I access the value attribute instead? Here is the dropdown select: <form [formGroup]="angForm" class="form-inline my-5 my-l ...

Angular Material Sidenav fails to cover the entire screen while scrolling

https://i.stack.imgur.com/32kfE.png When scrolling, the Sidenav is not expanding to take up 100% of the screen and it continues to scroll along with the page content. <div layout="column"> <section layout="row" flex> <!-- siden ...

Is there a method to reduce the requirement for if-conditions in this situation?

After revisiting this previous inquiry, I successfully implemented multiple filters on my observable, based on the user's chosen filters. However, the issue arises from the uncertainty of whether a filter is applied and the varying behavior of each f ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

Retrieve the color of the TripsLayer in deck.gl

layers.push(new TripsLayer({ id: 'trips', data: trips, getPath: (d: Trip) => d.segments.map((p: Waypoint) => p.coordinates), getTimestamps: (d: Trip) => d.segments.map((p: Waypoint) => p.timestamp), ...

Creating a responsive gallery using CSS techniques

I'm currently working on creating a simple gallery. My goal is to achieve the following design: https://i.sstatic.net/jq8pe.jpg However, the result I'm getting looks like this: https://i.sstatic.net/hSZyj.png The issue I'm facing is that ...

Developing an interactive single-page website

My goal is to develop a PHP web application with an overlay container that features dynamic fields/forms. The idea is for users to fill out the form without being redirected from the main page they are on. Imagine being able to report a page error on a w ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...