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().

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

Looking for a method to efficiently populate an array with values in Typescript

Here is an example of how I work with arrays in my code: var alphas: string[]; alphas = ['abc1', 'abc2', 'abc3']; // (this array can be changed) My modal class looks like this: export class Team { TeamName: string; } To ...

Guide to configure Validator to reject the selection of the first index option in Angular 2

When using a select option, it should be set up like: <div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success&ap ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

How do decorators within Angular 2 impact components?

Can you help me understand the purpose of decorators in angular2? How do they allow for annotating and modifying classes and properties during design time? It seems similar to using annotations, could you clarify this concept for me please? Thank you in ...

Premature conclusion of observable

I'm facing an issue with an element using the async pipe to subscribe to a Behavior Subject. showDiv$ = new BehaviorSubject<boolean>(false); showDivObv$ = this.showDiv$.asObservable().pipe( tap(() => console.log('here')), ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: My intention was to have the menu displayed below the content page while keeping the menu button visible. However, when I ran my app, it appear ...

What is the best way to implement a scroll event in a React application?

Can someone provide guidance on how to properly write the scrollHandler function for this scenario? ` useEffect(() => { document.addEventListener('submit', scrollHandler); return () => document.removeEventListener('scroll', ...

Guide to changing base 64 into a byte Array

Struggling to convert base64 to byte Array in Angular. Attempted solutions have not been successful. // Handling file upload handleUpload(event) { if (event.target.files[0]) { this.file = event.target.files[0].name; } const file = event.targ ...

How to Implement Multi Select Drag and Drop Feature in Angular 4?

Currently, I am implementing Angular 2 Drag-and-Drop from this library to enable the selection of list items using a drag and drop method. However, I have encountered issues with its functionality on touch devices and when attempting to perform multiple it ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

I encountered a problem while trying to install Angular Material within my Nx workspace

Currently in the process of setting up an Angular and React project within a Nx monorepo workspace. Encountering trouble while attempting to install Angular Material using npm i @angular/material I'm running Angular v16. Below is the specific error me ...

Bringing TypeScript modules from a local module into a React application

As I work on organizing my projects and keeping logic separate in components that will eventually be published, I have a specific structure set up for now: I have a library of Typescript scripts within a project named project-a A separate React app create ...

FIXED-IONIC 3: The 'questions' property is missing from the 'Object' type

Encountering an issue with a single line of code and exhausted all resources in attempts to resolve it. Seeking assistance for my simple quiz, disregarding the current data presentation. The trouble arises within my data.ts file, specifically at one parti ...

Using Google Fonts in a Typescript React application with JSS: A step-by-step guide

How can I add Google fonts to my JSS for use in styling? const styles = ({palette, typography}: Theme) => createStyles({ time: { flexBasis: '10%', flexShrink: 0, fontSize: typography.pxToRem(20) }, guestname: ...

The "export 'ɵɵcomponentHostSyntheticListener' (imported as 'i0') was not found in '@angular/core" error occurred during the Angular build

Trying to set up an Angular application with clarity UI. Using Angular version 10.1.1 and after adding clarity, encountering build errors. ERROR in ./node_modules/@clr/angular/esm2015/utils/animations/expandable-animation/expandable-animation.js 33:8-43 &q ...