Utilize function.apply in Typescript to pass generic parameters

For a personal project I've been working on (originally started in Javascript), I needed to make http requests. To streamline this process, I opted to use Axios and created a file called http.js with the code below:

import axios from 'axios';

const baseURL = '/api';

const requestWrapper = async (request, { url, options, data }) => {
  const config = { baseURL, ...options };

  const requestObject = await request.apply(
    this,
    data ? [url, data, config] : [url, config]
  );
  const requestData = requestObject.data;

  return { status: requestObject.status, data: requestData };
};

const get = async (url, options) => {
  try {
    return await requestWrapper(axios.get, { url, options });
  } catch (error) {
    return error.response;
  }
};

// More http request functions...

export { get, remove, post, put, patch };

In the previous snippet of code, I encapsulated each http request into its own function for easy management in case the http client library changes.

Now, I aim to convert this file to Typescript. My specific hurdle lies in passing a generic T through the Axios function within the wrapper function as shown here:

 const requestObject = await request.apply(
    this,
    data ? [url, data, config] : [url, config]
  );

I am unsure how to specify the generic in this context. Any suggestions on what I should do?

I have explored various solutions but haven't found anything that directly addresses my issue. One idea I considered is removing the internal wrapper and calling each Axios function within its respective encapsulation function.

Answer №1

When using Function#apply, which is weakly typed, you'll need to employ a type cast for a stronger type:

    const requestObject = await (request.apply(
        this,
        data ? [url, data, config] : [url, config]
    ) as ReturnType<typeof request<T>>)

Here is the full code snippet:

const requestWrapper = async <T>(request:
    typeof axios.get |
    typeof axios.post |
    typeof axios.put |
    typeof axios.patch |
    typeof axios.delete
    , { url, options, data }) => {
    const config = { baseURL, ...options };

    const requestObject = await (request.apply(
        this,
        data ? [url, data, config] : [url, config]
    ) as ReturnType<typeof request<T>>)
    const requestData = requestObject.data;

    return { status: requestObject.status, data: requestData };
};

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

There is an issue with the functionality of OrbitControls and dat.gui text

Incorporating three.js and dat.gui, I am utilizing a text property within my project. Additionally, my scene features OrbitControls: cameraControl = new THREE.OrbitControls(camera); cameraControl.update(); A complication arises in this particular setup. ...

Automate the process of opening an ngbpopover from an Angular 2 component using programming techniques

Currently, I am referring to this specific article in order to integrate Bootstrap with Angular 2. While the instructions in the article are helpful, there seems to be a lack of information on how to pass the popover reference to a component method. The on ...

Having trouble getting material-ui container to work with custom breakpoints in TypeScript?

Currently, I am exploring material-ui and typescript within my educational project. However, I have encountered a perplexing issue for which I am seeking assistance. In this project, I utilize custom breakpoints in the material-ui theme settings. import { ...

Effective strategies for utilizing AngularJS broadcast across various states within your application

Having issues with my editPrcChallenge function. I am broadcasting the challengekey in order to route the user to a child state, but for some reason it's not entering the function. Any thoughts on what might be wrong with my implementation? This is w ...

The second div element remains unselected in jQuery

Below is the example of an HTML structure: <span id="17">yes here</span> <div class="PricevariantModification vm-nodisplay"></div> <div class="PricesalesPrice vm-display vm-price-value"> <span class="a"></span> ...

"The issue I am facing is that the onSubmit function in Reactjs does not seem

I am currently working on a project using Reactjs with the nextjs framework. Right now, I am facing an issue with form validation in Reactjs. After clicking on the submit button, I am not receiving any alert message. Can anyone help me with this? I have ...

Rejuvenating your HTML content with AJAX over time

My HTML page contains links to charts that refresh every time the page is reloaded. A friend mentioned that AJAX can automatically refresh the chart at specified intervals without reloading the entire HTML page. I would appreciate any help with the HTML ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

Rails 7 is missing the Toast element from Bootstrap 5

Having some trouble with implementing Bootstrap 5 Toast in Rails 7 for flash messages. Here is the code I am currently using: # application.html.erb <head> ... <%= javascript_importmap_tags %> <script> const toastElList = document.que ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

Encountering a MongooseServerSelectionError: connection failure to 127.0.0.1:27017 while trying to connect to MongoDB

I am currently working on a basic node.js TypeScript API with MongoDB integration, and I am utilizing Docker to containerize the application. Below is a snippet from my index.ts file: import express from 'express'; import app from './app&ap ...

The "apply" function in Javascript cannot be found in the window.external extension object

Utilizing the javascript extension (known as window.external) in IE8 (or any IE version) to expose specific functions, I encountered an issue when attempting to call the apply function. Despite the belief that it is inherently available in every JS functio ...

The function applyMiddleware in React Redux is not working correctly

After thoroughly reviewing my code, I couldn't find any flaws, yet I received this error message: Uncaught TypeError: (0 , _reactRedux.applyMiddleware) is not a function import { applyMiddleware, createStore } from 'react-redux' impor ...

What impact does the size of the unpacked files have on the overall minified size of an npm package?

I've been working on shrinking the size of an npm package I created, and I've successfully reduced the unpacked size to around 210kb. https://www.npmjs.com/package/@agile-ts/core/v/0.0.12 <- 210kb https://www.npmjs.com/package/@agile-ts/core ...

Accessing several values in Angular by clicking

I have a dropdown that contains an input field and two more dropdowns. I am looking for a way to retrieve the values of all three fields when the search button is clicked. Screenshot https://i.sstatic.net/5Imaq.png Code HTML <nz-dropdown-menu #menu=&q ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

From mongoose to swagger: "<field>" validation error - BSONTypeError: The argument provided must be a string containing either 12 bytes or 24 hexadecimal characters

I'm currently working on developing a REST API using Express, Mongoose, and Swagger for API documentation. To automate the process of converting my existing schema to Swagger, I utilized the mongoose-to-swagger package. However, I encountered an issue ...

Extract the data from an HTML form and transfer the values into variables within a node.js function

Issue Description: I am facing a challenge in my project where I need to take three numbers as input from the user through an HTML form. Upon submission, I want these values to be passed to a node.js file and stored in variables. Here is the HTML code sni ...

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

The React Bootstrap modal fails to display the value of an argument passed through a parameter

I am currently working on a project that utilizes React for its front end development. Below is the code snippet: import React, {useState} from 'react'; import Tree from 'react-d3-tree'; import { useCenteredTree } from "./helpers&q ...