Eslint is back and it's cracking down on unused variables with no

I've configured eslint to alert me about unused variables

rules: {
  '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
}

Presently, I have a TypeScript class structured like this:

import { User } from './user';

export class MyClass {
  async myMethod(): Promise<User> {
    // Some code
  }
}

Upon running eslint, I encounter the following error message:

error  'User' is defined but never used  @typescript-eslint/no-unused-vars

I'm puzzled by eslint's warning. To me, it seems like the variable is being utilized.

Answer №1

When looking at the example provided, it's important to note that the type Promise is used to define a type and not necessarily indicate that User is being used in your Method. Eslint expectations are as follows:

import { IUser} from './user'; // interface for User object
import { User } from './user'; // User object

export class MyClass {
  async myMethod(User: string): Promise<IUser> {
    // Some code with User parameter
  }
}

In this case, your Eslint rule will only apply to the User object and not the interface.

For further information, you may refer to:

Answer №2

To prevent inaccurate error reporting, it is recommended to deactivate the base rule. For more information, please refer to: Deactivating Base Rule

  "no-unused-vars": "off",
  "@typescript-eslint/no-unused-vars": ["error", { args: "none" }]

UserModel.ts

export class UserModel {
    username: string;
}

MyComponent.ts

import { UserModel } from './UserModel'

export class MyComponent {
    async myFunction(): Promise<UserModel> {
        // Some code here
    }
}

Below is a simplified version of my eslint configuration

module.exports = {
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint/eslint-plugin"],
  "env": {
    "node": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module"
  },
  "rules": {
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": ['error'],
  }
}

dependencies in package.json

{
  "scripts": {
    "lint": "eslint app.ts"
  },
  "devDependencies": {
    "@types/eslint": "7.2.4",
    "@types/node": "13.7.7",
    "@typescript-eslint/eslint-plugin": "4.14.1",
    "@typescript-eslint/parser": "4.14.1",
    "eslint": "7.18.0",
    "ts-node": "8.6.2",
    "typescript": "3.8.3"
  }
}

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

Best practices for handling HTTP requests in Angular 5

I'm currently developing multiple applications using Angular 5. My aim is to adhere to all the dos and don'ts of Angular. However, I'm facing some confusion regarding a few things. 1) What is the difference between this... this._http.g ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Using regular expressions, you can eliminate a specific segment of a string and substitute

Provide a string in the following format: lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone I am creating a function that will extract the specified address parts and remove any extra parts while maintaining maxim ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...

The Angular RXJS HTTPClient fails to properly handle HttpErrorResponses

In my Angular 12 project, I am facing an issue with setting up unit tests that should capture errors from HTTP responses. However, when running the tests, instead of receiving the error as an actual error object, it is being passed within the response body ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

"Utilizing FormData in an IONIC 5 project with

While creating a user profile, I am encountering an issue where the FormData being generated for sending is empty despite all other fields having values. Below is the code snippet from cadastro.ts: import { Component, OnInit } from '@angular/core&ap ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

Contrast between utilizing and publishing, demanding and bringing in within Express

I have recently started learning Typescript and Express. I have a simple exported function that looks like this: export function testFunction(req: any, res: any) { console.log(req.body); return res.status(200).send('OK'); }; And ...

Tips for integrating tsconfig with webpack's provide plugin

In my project, I have a simple component that utilizes styled-components and references theme colors from my utils.tsx file. To avoid including React and styled-components in every component file, I load them through WebpackProvidePlugin. Everything works ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor. This is the code snippet for the directive: import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit ...

Creating cohesive stories in Storybook with multiple components

I need assistance with my storybook setup. I have four different icon components and I want to create a single story for all of them instead of individual stories. In my AllIcons.stories.tsx file, I currently have the following: The issue I am facing is ...

Tips on narrowing down the type of callback event depending on the specific event name

I've been working on implementing an event emitter, and the code is pretty straightforward. Currently, tsc is flagging the event type in eventHandler as 'ErrorEvent' | 'MessageEvent'. This seems to be causing some confusion, and I ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Guide on saving a PDF file after receiving a binary response using axios

Is there a way to save a PDF file from a binary response received through an axios get request? When making the request, I include the following headers: const config: AxiosRequestConfig = { headers: { Accept: 'application/pdf', respon ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...