Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue.

I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic.

ESLint: Unexpected any. Specify a different type.(@typescript-eslint/no-explicit-any)

ESLint suggested replacing any with the never type in the generic definition.

https://i.stack.imgur.com/B38xa.png

I was familiar with never being used to indicate a lack of parameters or return values. Can it really replace any in generics?

source

import axios, { AxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios';
import { stringify } from 'qs';
import { FilterParams } from '@src/interfaces/services/type';

type MethodType = <T = any, R = AxiosResponse<T>, D = any>(
  url: string,
  data?: D | undefined,
  config?: AxiosRequestConfig<D>,
) => Promise<R>;

class AxiosClient {
  options: AxiosRequestConfig;
  client: AxiosInstance;
  get: MethodType;
  post: MethodType;
  patch: MethodType;
  delete: MethodType;

  constructor() {
    this.options = {
      baseURL: process.env.API_ROOT || '/api/',
      withCredentials: true,
      paramsSerializer: (params: FilterParams) =>
        stringify(params, { arrayFormat: 'repeat' }),
    };
    this.client = axios.create(this.options);

    /* method redefinition */
    this.get = this.client.get;
    this.post = this.client.post;
    this.patch = this.client.patch;
    this.delete = this.client.delete;
  }
}

export default new AxiosClient();

Answer №1

Check out the typescript-eslint documentation related to this specific rule.

When it comes to using never, the hint on the rule implies that you may not necessarily care about the type. However, in my opinion, that might not be applicable in this scenario.

While any types are viable in Typescript, opting for a literal definition of D as anything can still be a valid approach. The existence of this rule stems from the lack of type safety associated with the usage of any, prompting the importance of explicitly defining types when possible. Despite this, if incorporating any aligns with your organization's coding standards, disabling this particular rule could be an option worth considering. On the other hand, if adhering to this rule is crucial, exploring alternative options such as unknown or string | object might prove equally effective in this context.

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

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

Understanding the correct way to map two arrays with boolean values is essential for effective data

My situation involves two lists: accounts and accountsWithSelectedField. I initially mapped accountsWithSelectedField like this: this.accountsWithSelectedField = this.accounts.map(s => ({...s, selected: false})); Subsequently, upon receiving a list of ...

Customizing page layout for pages wrapped with higher-order components in TypeScript

Looking to add a layout to my page similar to the one in this link: layouts#per-page-layouts The difference is that my page is wrapped with a HOC, so I tried applying getLayout to the higher order component itself like this: PageWithAuth.getLayout Howev ...

The Tailwind CSS Chrome extension is causing disruptions on the websites I view

Currently, I am in the process of creating a chrome extension using various tools like React, Typescript, TailwindCSS, and a custom Webpack configuration. To enhance user experience, I have modified the default action in manifest.json so that clicking on t ...

Utilizing server-side caching middleware with tRPC version 10

Currently, I am working on a Next.js project and exploring the possibility of incorporating in-memory caching for tRPC results. Each tRPC procedure should have the option to set a custom TTL for caching purposes. My initial thought is that utilizing tRPC&a ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Guide to integrating a component within another component

Due to the size of this application, I am unable to utilize app.module. Unfortunately, the component I need to implement does not contain a module file. I have attempted to import it and utilize @NgModule, but it has not been successful. An error occur ...

Break down the provided Array type into distinct new types

If we have a specific type defined as: type Tuple = [name: string, age: number, address: string]; and we are interested in creating a new type without the first element, like this: type NewTuple = [age: number, address: string]; Is there a way to achieve ...

The element 'loginToken' is not found within the type '{ loginToken: string; } | { error: Error; } | { username: string; password: string; }'

I'm currently working on creating a reducer using Typescript and Redux, but I keep running into this error: Property 'loginToken' is not recognized in type '{ loginToken: string; } | { error: Error; } | { username: string; password: str ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript: Typescript version: 5.2.2 type A = { a: number; b: string }; // incorrect const buildPartialBad = (key: keyof A, val: A[keyof A ...

"Null value is no longer associated with the object property once it has

What causes the type of y to change to string only after the destruction of the object? const obj: { x: string; y: string | null } = {} as any const { x, y } = obj // y is string now ...

A collection of JSON data containing various diverse values

My classes are not specific and they look like this: type SyncReducerAction<TState> = (state: TState, ...args: any[]) => TState; type AsyncReducerAction<TState, TResult, TRest extends any[]> = { promise: (...args: TRest) => Promise< ...

What could be causing Typescript Compile Errors to occur during runtime?

In the Visual Studio React + Redux template project, I have created a react component with the following "render()" method: public render() { return ( <React.Fragment> <h1>Welcome to the Adventure Company {th ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...

No declaration file was located for the module '@handsontable/react' despite the presence of a 'd.ts' file

Embarking on a fresh project using vite+react+ts+swc by executing the command below as per the vite documentation. npm create vite@latest -- --template react-swc-ts Additionally, I integrated the handsontable library into my setup with the following comm ...

Guide to building an interface for an object containing a nested array

While working on my Angular/TypeScript project, I encountered a challenge in processing a GET request to retrieve objects from an integration account. Here is a snippet of the response data: { "value": [ { "properties": { ...

Troubleshooting Ionic 4 IonSlides slideTo and getActiveIndex functionalities encountering issues within IonTab context

I am encountering an issue with my ion slides setup on a page. Here is the code snippet: <ion-slides #schemasliderref [options]="schemaSliderOpts" (ionSlideDidChange)="slideChange()"> <ion-slide *ngFor="let schemaImage of schemaImages; let i ...

Instructions on utilizing type interfaces for prop drilling in my React Typescript counter

I am currently developing a basic counter app to monitor my progress in a digital card game that I enjoy playing. While attempting to pass props from the parent component to the child component, I encountered an issue where the props were not being success ...