Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json:

{
  "root": true,
  "ignorePatterns": ["projects/**/*"],
  "overrides": [
    {
      "files": ["*.ts"],
      "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates",
        "plugin:prettier/recommended"
      ],
      "rules": {
        "no-unused-vars": "error",
        "@typescript-eslint/no-unused-vars": "error",
        "@typescript-eslint/explicit-member-accessibility": "error",
        "@angular-eslint/directive-selector": [
          "error",
          {
            "type": "attribute",
            "prefix": "app",
            "style": "camelCase"
          }
        ],
        "@angular-eslint/component-selector": [
          "error",
          {
            "type": "element",
            "prefix": "app",
            "style": "kebab-case"
          }
        ]
      }
    },
    {
      "files": ["*.html"],
      "extends": ["plugin:@angular-eslint/template/recommended"],
      "rules": {}
    },
    {
      "files": ["*.html"],
      "excludedFiles": ["*inline-template-*.component.html"],
      "extends": ["plugin:prettier/recommended"],
      "rules": {
        "prettier/prettier": ["error", { "parser": "angular" }]
      }
    }
  ]
}

angular component:

export class AppComponent {
  public title = 'angular-movieseat';
  public something = 'asd';

  public somethingFn() {
    console.log('something');
  }
}

The variables something and somethingFn() in the Angular component are never used, but ESLint does not flag them as unused. How can these class variables be flagged as unused? ESLint works for other rules like explicit-member-accessibility.

For completeness, here is my tsconfig.json file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": ["ES2022", "dom"]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Answer №1

Angular presents a unique challenge as we can access component variables and methods directly inside the HTML file of the component, which ESLint may not pick up on, resulting in no error being displayed. To properly address this issue, manual verification of variables and methods is necessary by comparing their usage in both the HTML and TS files.

It is recommended to conduct a thorough global search for the variable name to uncover all instances of its usage. Additionally, checking the parent component to see if the property is accessed via ViewChild is also advised.

Answer №2

It seems that ESLint and Angular don't quite get along:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public title = 'angular-movieseat';
  private something = 'asd';

  private somethingFn(): void {
    console.log('something');
    const something = 'something';
  }
}

Upon declaring the const something, an expected error is triggered for being an unused variable. The same issue occurs with the Input import at the beginning of the file.

Warnings are also raised for using private on something and somethingFn().

https://i.sstatic.net/od1Iv.png

Answer №3

Based on the information provided, it seems like your .eslintrc.json file should include the following adjustments:

"files": ["*.ts"],
      "parserOptions": {
        "project": ["tsconfig.json"],
        "createDefaultProgram": true
      },
      "plugins": ["@typescript-eslint"],

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

Issues arise when upgrading from Angular 8 to 9, which can be attributed to IVY

After successfully upgrading my Angular 8 application to Angular 9, I encountered an error upon running the application. { "extends": "./tsconfig.json", "compilerOptions": { "outDir": ". ...

Try using ngFor within the insertAdjacentHTML method

When a user clicks, I dynamically attach an element inside a template like this: this.optionValue = []; youClickMe(){ var moreput = ''; moreput += '<select">'; moreput += '<option *ngFor="let lup of opti ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Create a distinct style for material inputs without relying on ng-deep, !important declarations

I am looking to customize the appearance of a material input by making it round with border radius. I found a solution that involves adding a class "custom-search" to the mat-form-field and applying the necessary styles in the global stylesheet: .custom-se ...

"Authentication guard does not sit idle while waiting for the observable

My issue involves the auth guard service constructor(private _auth: AuthService, private _router: Router) { } canActivate() { if(this._auth.isLoggedIn()){ return true; } else { this._router.navigate(['/login']); ret ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

TS Mapped Type: Dynamically exclude specific keys based on their values

Seeking a method to create a mapped type that excludes specific keys based on the value of the mapped key. For instance: Consider an option: Options struct, where Options is a union type defined as: { type: DataType } or { type: DataType, params: DataPar ...

What methods can be used to display data using TypeScript's Optional Chaining feature?

I came across this Try it Yourself TypeScript Optional Chaining example in W3Schools TypeScript Null & Undefined section, and I have attached a screenshot for reference. The example demonstrates that when data is undefined, it displays No Yard. Howeve ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

Steps for developing a Global service in Angular

I've come across many discussions on global angular services, but none seem to truly embody the concept of "global". I'm curious if it's feasible to develop a service that doesn't require importing everywhere it's used (i.e. truly ...

Having issues transferring files from Angular 8 to NodeJS

After successfully implementing a component for drag and drop file functionality using Angular, I encountered an issue when trying to create a service for server requests. The DragDropDirective is as follows: // Code for DragDropDirective import { Direct ...

Tips for resolving the undefined error in TypeScript and React

Hey, I have this code snippet below which includes a call to the isSomeFunction method that returns true or false. However, there are times when the argument can be undefined. I only want to execute this function if selectedItems is not undefined. How can ...

Is there a way to modify a component's CSS by using a global CSS class name in Angular?

We have implemented a system where a class on the html element determines whether the user is in dark or light mode of the application. <html class="dark-mode"></html> This class is dynamically added using Renderer2 in a service that detects ...

What is the correct way to write SVG markup within SVG tags in a React and NextJS environment?

I currently have a Svg component set up like this interface SvgIconProps { children: React.ReactNode; strokeWidth?: number; width?: number; height?: number; className?: string; } export const SvgIcon = ({ children, strokeWidth = 1, width = ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Struggling to launch on Vercel and encountering the error message, """is not allowed by Access-Control-Allow-Origin. Status code: 204""

Greetings! I trust you are doing well. Currently, I am engrossed in developing a full-stack application. The app runs smoothly on localhost without any issues. However, upon deploying both the server and front end on Vercel, a snag arose when attempting to ...

Upgrade all dependencies within the organization's Angular scope in the package.json file to the latest version available

My current package.json dependencies include: "@angular/animations": "^5.0.0", "@angular/cdk": "^5.2.0", "@angular/common": "^5.0.0", "@angular/compiler": "^5.0.0", "@angular/core": "^5.0.0", "@angular/flex-layout": "^2.0.0-beta.12", "@angular/forms": "^5 ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

A step-by-step guide to customizing the Material UI Chips delete SVG icon to appear in white color through

Using a Material UI component, I added a custom class to my chip. Attached is a screenshot showing what I mean. Currently, I am attempting to change the color of the cross button to white. After inspecting the element, I discovered that it is an SVG ico ...